# \[SOLVED\] Getting timer remaining time

**URL:** <https://community.openhab.org/t/solved-getting-timer-remaining-time/87501>\
**Category:** Scripts & Rules\
**Created:** [December 12, 2019, 9:59pm UTC](https://community.openhab.org/t/solved-getting-timer-remaining-time/87501 "2019-12-12T21:59:41Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![enboig](https://community.openhab.org/letter_avatar_proxy/v4/letter/e/3be4f8/32.png) [@enboig](https://community.openhab.org/u/enboig)\
**Post date:** [December 12, 2019, 9:59pm UTC](https://community.openhab.org/t/solved-getting-timer-remaining-time/87501/1 "2019-12-12T21:59:42Z")

</div>

I want to show how much time before a timer runc, but as long as I see it is impossigle ([Determine Timer Elapsed or Remaining](https://community.openhab.org/t/determine-timer-elapsed-or-remaining/5724)) has something changed in these nearly 4 years?

---

<div class="post-metadata">

**Author:** ![rossko57](https://community.openhab.org/user_avatar/community.openhab.org/rossko57/32/70263_2.png) [@rossko57](https://community.openhab.org/u/rossko57)\
**Post date:** [December 12, 2019, 10:05pm UTC](https://community.openhab.org/t/solved-getting-timer-remaining-time/87501/2 "2019-12-12T22:05:31Z")

</div>

Nope, nothing changed.

One alternative approach -

> [@Design Pattern : Expire Binding based Countdown timer](https://community.openhab.org/t/design-pattern-expire-binding-based-countdown-timer/49225):
>
> Problem Statement Sometimes you need to run a timer, but want to able to inspect the remaining time. This is not directly possible with either createTimer() or the Expire binding. Example - I have lighting-on timers that run for different duration depending on the trigger source or time of day. It is useful to have the timer behave “intelligently” - do not apply a new 5-minute request where there is still seven minutes of a previous trigger to run. But do apply it if there is only two minu…

Another -

> [@Design Pattern: Looping Timers](https://community.openhab.org/t/design-pattern-looping-timers/47699):
>
> Edit: Update for OH 4 Please see [Design Pattern: What is a Design Pattern and How Do I Use Them](https://community.openhab.org/t/design-pattern-what-is-a-design-pattern-and-how-do-i-use-them/40319) to understand the scope and purpose of this and other Design Patterns. Problem Statement Often one may require a loop in a Rule, to wait for some event to occur or some state to change before doing something. For example, if a door is opened for a long time to send an alert every hour until the door is closed. Concept Use a Timer that reschedules itself instead of a while loop or sleeps. …

---

<div class="post-metadata">

**Author:** ![rlkoshak](https://community.openhab.org/user_avatar/community.openhab.org/rlkoshak/32/75251_2.png) [@rlkoshak](https://community.openhab.org/u/rlkoshak)\
**Post date:** [December 12, 2019, 10:21pm UTC](https://community.openhab.org/t/solved-getting-timer-remaining-time/87501/3 "2019-12-12T22:21:15Z")

</div>

If you use Scripted Automation, I submitted a countdown timer module to the [Python Helper Libraries](https://openhab-scripters.github.io/openhab-helper-libraries/index.html).

> <https://github.com/openhab-scripters/openhab-helper-libraries/pull/237>
>
> This is a module that has a class to implement a countdown timer. It creates a t…imer that loops every second, updating a passed in Item with the amount of time left on the Timer so people can see how much time is left on their sitemaps and such. 
> 
> A Number Item or a String Item can be passed to receive the time left updates. If a Number, the number of seconds (rounded to the nearest second) remaining updates the Item. If a String Item, the result of str on the datetime.timedelta Item get's returned, again rounded to the nearest second. The timer itself though will expire on the scheduled millisecond 
> 
> Signed-off-by: Rich Koshak \<rlkoshak@gmail.com\>

It’s largely based on rossko57’s original Rules DSL idea but doesn’t use Expire. You just need to copy it to your automation folder and instantiate it in a Rule, passing it the time duration, the function to call when it expires, and an Item to update every second while the timer counts down.

---

<div class="post-metadata">

**Author:** ![enboig](https://community.openhab.org/letter_avatar_proxy/v4/letter/e/3be4f8/32.png) [@enboig](https://community.openhab.org/u/enboig)\
**Post date:** [December 12, 2019, 10:33pm UTC](https://community.openhab.org/t/solved-getting-timer-remaining-time/87501/4 "2019-12-12T22:33:48Z")

</div>

Wow! I have a lot to learn to keep up!  
I am having some trouble with a timer because of a _not as good as expected_ humidity sensor.  
I have a fan in bathroom to remove humidity after shower, but some time my sensors halt so I cannot run a trigger “if humidity higher than”, so I started playing with timers setting and rescheduling “on sensor update”, but then … and then …  
So I was searching for a way to get information and debug. Most of time I end with telegram bot messages, but I was looking for a way to publish this info on sitemap.  
I will have to take a look at next generation rule engine.

Thanks to both of you

---

<div class="post-metadata">

**Author:** ![mstormi](https://community.openhab.org/user_avatar/community.openhab.org/mstormi/32/55857_2.png) [@mstormi](https://community.openhab.org/u/mstormi)\
**Post date:** [December 12, 2019, 11:00pm UTC](https://community.openhab.org/t/solved-getting-timer-remaining-time/87501/5 "2019-12-12T23:00:46Z")

</div>

> [@enboig](#):
>
> so I started playing with timers

consider using persistence and a moving average

---

<div class="post-metadata">

**Author:** ![rossko57](https://community.openhab.org/user_avatar/community.openhab.org/rossko57/32/70263_2.png) [@rossko57](https://community.openhab.org/u/rossko57)\
**Post date:** [December 12, 2019, 11:13pm UTC](https://community.openhab.org/t/solved-getting-timer-remaining-time/87501/6 "2019-12-12T23:13:14Z")

</div>

> [@enboig](#):
>
> So I was searching for a way to get information and debug.

You probably don’t need these complicated countdown timers then. Just a fixed length timer to be started or rescheduled? Place logInfo()s in your rule(s) to drop useful messages, so that you can follow what is going on in your `openhab.log`

---

<div class="post-metadata">

**Author:** ![michalp](https://community.openhab.org/letter_avatar_proxy/v4/letter/m/47e85d/32.png) [@michalp](https://community.openhab.org/u/michalp)\
**Post date:** [January 22, 2020, 2:34pm UTC](https://community.openhab.org/t/solved-getting-timer-remaining-time/87501/7 "2020-01-22T14:34:58Z")

</div>

Hi,

I try to implement this Countdown Timer. Generaly it works, but I don’t know how to cancel it if the switch goes OFF before time expires.

```csv
import time
import personal.countdown_timer
reload (personal.countdown_timer)
from personal.countdown_timer import CountdownTimer
from core.log import log_traceback, logging, LOG_PREFIX
from datetime import datetime, timedelta
log = logging.getLogger("{}.TEST.countdown_timer".format(LOG_PREFIX))

from core.rules import rule
from core.triggers import when

func_called = False

def test():
    global func_called
    func_called = True

number = "alarmTime" // number Item for countdown
delay_item = "alarmDelay" // switch Item for starting countdown

@rule("Countdown timer", description="Start countdown for getting out")
@when("Item alarmDelay received update")
def countdown_timer(event):
    if((items[delay_item]) == ON):
        timer = CountdownTimer(log, (datetime.now() + timedelta(seconds=10)), test, number)
        time.sleep(0.1)

# elif((items[delay_item]) == OFF):
# log.info("Cancel...")
# timer.cancel()
 

```

If I try to do else or elif timer.cancel, I got local variable ‘timer’ referenced before assignment error. As I am total noob in python, could you please show me some example how it should be implemented?

---

<div class="post-metadata">

**Author:** ![rlkoshak](https://community.openhab.org/user_avatar/community.openhab.org/rlkoshak/32/75251_2.png) [@rlkoshak](https://community.openhab.org/u/rlkoshak)\
**Post date:** [January 22, 2020, 2:45pm UTC](https://community.openhab.org/t/solved-getting-timer-remaining-time/87501/9 "2020-01-22T14:45:56Z")

</div>

`timer.cancel()`

---

<div class="post-metadata">

**Author:** ![michalp](https://community.openhab.org/letter_avatar_proxy/v4/letter/m/47e85d/32.png) [@michalp](https://community.openhab.org/u/michalp)\
**Post date:** [January 22, 2020, 2:49pm UTC](https://community.openhab.org/t/solved-getting-timer-remaining-time/87501/10 "2020-01-22T14:49:38Z")

</div>

Thanks,

but if I try to use it:

```csv
   elif((items[delay_item]) == OFF):
       log.info("Cancel...")
       timer.cancel()

```

I got error:

`2020-01-22 15:48:07.685 [ERROR] [jsr223.jython.Countdown timer] - Traceback (most recent call last): File "/etc/openhab2/automation/lib/python/core/log.py", line 51, in wrapper return fn(*args, **kwargs) File "<script>", line 31, in countdown_timer UnboundLocalError: local variable 'timer' referenced before assignment`

---

<div class="post-metadata">

**Author:** ![rlkoshak](https://community.openhab.org/user_avatar/community.openhab.org/rlkoshak/32/75251_2.png) [@rlkoshak](https://community.openhab.org/u/rlkoshak)\
**Post date:** [January 22, 2020, 3:35pm UTC](https://community.openhab.org/t/solved-getting-timer-remaining-time/87501/11 "2020-01-22T15:35:59Z")

</div>

You have to declare timer as a global variable.

---

<div class="post-metadata">

**Author:** ![michalp](https://community.openhab.org/letter_avatar_proxy/v4/letter/m/47e85d/32.png) [@michalp](https://community.openhab.org/u/michalp)\
**Post date:** [January 22, 2020, 3:54pm UTC](https://community.openhab.org/t/solved-getting-timer-remaining-time/87501/12 "2020-01-22T15:54:31Z")

</div>

Really don’t know how to do it correctly. This couses to run timer just when script is loaded, it is possible to cancel it, but can’t be started with error `TypeError: 'CountdownTimer' object is not callable`

```csv
def test():
    global func_called
    func_called = True

number = "alarmTime"
delay_item = "alarmDelay"

timer = CountdownTimer(log, (datetime.now() + timedelta(seconds=10)), test, number)

@rule("Countdown timer", description="Start countdown for getting out")
@when("Item alarmDelay received update")
def countdown_timer(event):
    if((items[delay_item]) == ON):
           timer.cancel()
           timer()
        time.sleep(0.1)

    elif((items[delay_item]) == OFF):
             log.info("Cancel...")
            timer.cancel()

```

---

<div class="post-metadata">

**Author:** ![rlkoshak](https://community.openhab.org/user_avatar/community.openhab.org/rlkoshak/32/75251_2.png) [@rlkoshak](https://community.openhab.org/u/rlkoshak)\
**Post date:** [January 22, 2020, 3:58pm UTC](https://community.openhab.org/t/solved-getting-timer-remaining-time/87501/13 "2020-01-22T15:58:23Z")

</div>

```python
number = "alarmTime"
delay_item = "alarmDelay"

timer = None

@rule("Countdown timer", description="Start countdown for getting out")
@when("Item alarmDelay received update")
def countdown_timer(event):
    global timer
    if((items[delay_item]) == ON):
        timer = CountdownTimer(log, (datetime.now() + timedelta(seconds=10)), test, number)
        time.sleep(0.1)

    elif((items[delay_item]) == OFF):
             log.info("Cancel...")
            timer.cancel()

```

---

<div class="post-metadata">

**Author:** ![michalp](https://community.openhab.org/letter_avatar_proxy/v4/letter/m/47e85d/32.png) [@michalp](https://community.openhab.org/u/michalp)\
**Post date:** [January 22, 2020, 4:06pm UTC](https://community.openhab.org/t/solved-getting-timer-remaining-time/87501/14 "2020-01-22T16:06:26Z")

</div>

> [@rlkoshak](#):
>
> global timer

Aaah… Thanks, it is working OK now!  
as I said - I’m total noob with this.
