Difference between 'timer = null' and 'timer.cancel()'?

Hey there =)

In the past days I had some problem with my timers. I noticed that all the examples (Example: Android App | openHAB) do use

timerAlarm.cancel
timerAlarm = null

for cancelling a timer while I only used timerAlarm = null. Since I use both of these commands my issues are gone.

Now I am wondering…

  • what the difference between these command is,
  • if and why both are commands are needed and
  • if the order of them is important?

Do you think this information is worthy to be added to the section Timers on Actions | openHAB?

This variable is only a ‘handle’, a ‘pointer’, a reference to a fully independent scheduled timer. Setting the variable to null has no effect on an existing timer. However, the handle (when still valid!) allows you to communicate with the timer, by sending cancel, reschedule etc.

Many rule authors use setting handle to null just as a convenient indicator that some previously defined timer is now finished with. That’s a really useful trick, but has nothing to do with documented timer syntax.

1 Like

Interesting. Thank you for the clarification!

May I add some parts of your explanation to the documentation of timers in the docs? I think this might be interesting for others as well.

If you wish.
But remember createTimer just offers you a handle. You do with that what you wish - ignore it, or put it in a variable of your choice. Managing the variable is not part of the timer’s lifecycle.

1 Like

This is nothing special to timers. Be aware that OH is based on Java and the JVM. So timers are nothing special. They are just Java objects that get created by the new operator. And that is what createTimer does behind the scenes. It creates a Java object of the type Timer.

The new operator returns the object reference after creation and usually your program stores the reference into one or more variables. Because Java is designed with an implicit lifecycle, you cannot destroy a created Java object actively. The JVM for this reason keeps track of how many references each created objects currently has. If the application no longer holds any reference, the object get’s eventually destroyed by the garbage collector of the JVM-

That leaves only the question, on how to get rid of a reference. And that is the assignment with null. This decreases the reference count to the object by one.

So once more. This is nothing special about timers. It’s just the way how Java defines objects and their lifecycle from creation until destroyment.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.