Contdown for timer

For me as not being a developer, it’s a bit tricky to present a countdown time for an alarm set in OH.

Based on the alarm clock example in the wiki, I created a timer. After creating the timer, the command startCountdown.sendCommand(ON) - and hence the rule “Countdown” is executed (cf. below).

This works perfectly until I change the alarm time, which executes the Conuntdown rule a second time.

How can I kill the thread in the rule? Or what alternative means would I need to take?

Thx in advance, G.


rule “Countdown”
when

Item startCountdown received command ON

then

var totalSecs = iZeitBisAlarm * 60

while(totalSecs >= 0) {
	var int hours = totalSecs / 3600
	var int minutes = (totalSecs % 3600) / 60
	var int seconds = totalSecs % 60

	var String timeString =
		String::format("%02d", hours) + ":" +
		String::format("%02d", minutes)  + ":" +
		String::format("%02d", seconds)

    weckerZeitMessage.postUpdate(sAlarmZeit + " - noch " + timeString + " bis zum Alarm")

    totalSecs = totalSecs - 1
    **Thread::sleep(1000)**
}

end

Would you like to create an alarm clock?

I do not recommend the while loop; but rather use a real timer. If you change the alarm time you can cancel it re-create it. You also need to take care that if you update the alarm time via UI that you use a lock. My Alarm clock is based on the “Alarm Clock - Example II” in AlarmClock

I’ll add some additional comments to this wiki example code - I hope it will help you.

Old discussion thread (with example) on how to realize an alarm clock:
How to configure openHAB for setting alarm/schedule times thru the UI

Apart from that, I would suggest to make totalSecs a global var, i.e. define it ahead the rules.
Then you could test if (totalSecs > 0) and set to the new value without starting a new thread…

Thanks a lot for your answers. I have based my alarm clock on the wiki example and it works fine.

My issue starts when I try to extend the item showing the alarm time with an additional part which counts down the time until the alarm fires, e.g. Alarm 05:30 Uhr - remainig time to alarm 23:23:45 h.

The while-loop is indeed a bad idea as it continues when I reset the alarm time. Is this because we add a lock to the rule? And if I add another timer to countdown - how would I do this conceptually?

The first thing you should keep in mind, openHAB refreshes the UI (at least classic UI) only 2 times a minute, so you will never see every second.
Although this might be configurable (I don’t remember that), a shorter refresh-time would increase cpu-time.

A possible approach could be a (separate) rule which fires every 30 seconds (Time cron "0/30 * * * * ?") and updates the item only if countdown is active.