Calculated daily run time of a switch

Hi there

I want to log the daily run time (i.e. in minutes) of a warmer which I have connected to a switch.

The switch is simply defined in .items as “Switch Greenhouse_Warmer …” (it is coupled to a zwave flush switch) - and it is turned ON and OFF by a rule looking at temperature readings once every few minutes. That part all works.

How should I do this run-calculation most easily ? I am sure one of you guys have something like this and can share the code ?

I am on OH1 - but that is probably not relevant here…

I’m relatively new to OH and this might not be the best approach, but I would do something like this.

rule “add to count”
When
Time cron "0 0/1 * * * * "
then
if (device.state == ON){
var itemMinuteCounter = itemMinuteCounter+1
sendCommand(itemMinuteCounter,var)
}
end

You’d also need to set up persistence for itemMinuteCounter. I’m sure there are errors in my syntax, but hopefully this helps.

You may be able to pick up some ideas from this thread:

I have looked at the examples - and I do get how they are set up. It just seem far too complicated for what I am trying to achieve…?

Is there no simple formula where you can get the millis/minutes between two state changes of an item ? something like …now.timestamp minus previousstage.timestamp?

Creating cron jobs running every second or minute to check states seem like overkill ?

OK - came up with a better solution, inspired by older examples and google. Although the example has too much logging etc. - it does works and without running crons every second/minute:

rule "Drivhus2_Warmer started"
	when
		Item Drivhus2_Warmer received command ON
	then
		logInfo("DrivTemp", "Warmer on")
		postUpdate(Drivhus2_Warmer_LastOnState, new DateTimeType())
	end

rule "Drivhus2_Warmer stopped"
	when
		Item Drivhus2_Warmer received command OFF
	then
		var DateTimeType prevOnState = Drivhus2_Warmer_LastOnState.state as DateTimeType
		var Number execDuration = Seconds::secondsBetween(new DateTime(prevOnState.calendar.timeInMillis), now ).getSeconds()
		logInfo("DrivTemp","The warmer is now off after runnung for " + execDuration + " secs.")
		postUpdate(Drivhus2_Warmer_Last_Runtime_Sec, execDuration)
		var Number dailyTotalSeconds = execDuration + Drivhus2_Warmer_Today_Runtime_Sec.state as Number 
		postUpdate(Drivhus2_Warmer_Today_Runtime_Sec, dailyTotalSeconds)
		var Number dailyTotalMinutes = dailyTotalSeconds / 60
		postUpdate(Drivhus2_Warmer_Today_Runtime_Min, dailyTotalMinutes)
	end
	
rule "Drivhus2_Warmer Daily Reset"
	when
		Time cron "0 0 0 * * ?"
	then
		sendCommand(Drivhus2_Warmer_Today_Runtime_Sec, 0)
		sendCommand(Drivhus2_Warmer_Today_Runtime_Min, 0)
		logInfo("DrivTemp","Daily runtime counters reset to 0")
	end