please see parts of my implemented rule:
# Set latest End Time
events.sendCommand(ir.getItem(item.name + '_EndTime'), ZonedDateTime.now().toLocalDateTime().toString())
# Calculate latest Running Time
dtStartTime = ir.getItem(item.name + '_StartTime').state.getZonedDateTime()
dtEndTime = ir.getItem(item.name + '_EndTime').state.getZonedDateTime()
if isinstance(ir.getItem(item.name + '_RunningTime').state, UnDefType):
longRunningTimeExecuted = 0
longRunningTimeExecuted = ir.getItem(item.name + '_RunningTime').state.intValue()
longRunningTime = dtStartTime.until(dtEndTime, ChronoUnit.MINUTES) + longRunningTimeExecuted
The Endtime was set to 0 (1970-01-01T00:00Z) by another rule before.
When I’m looking in the UI, I can see that the EndTime item has the expected value. But the RunningTime is calculated on the basis of 1970-01-01T00:00Z
Does the update of the item take longer time then the processing of the next lines of code?
Basically the answer is yes. OH processes
sendCommand asynchronously, so the call to
sendCommand returns before the update is done.
One way is to set a variable and use that in the rule…
dtEndTime = ZonedDateTime.now().toLocalDateTime().toString()
events.sendCommand(ir.getItem(item.name + '_EndTime'), dtEndTime)
You can then reference
dtEndTime as required, independently of the
item.name + '_EndTime'
I just want to add that the same is true for postUpdate. The call to sendCommand and postUpdate generates an event that gets put on the bus and processed in the background. You will pretty much never have a case where you send a command or post an update to an Item and on the next line see that reflected in the Item’s state.
One further gotcha is that the Item’s state is not guaranteed to change in response to a command. Some commands cannot be held in an Item as a state (e.g. INCREASE/DECREASE, UP/DOWN/STOP, etc.). Items can be configured to not update the state of the Item until after the end device reports that it has changed state (see the Autoupdate Item metadata).