Timing Problems on startup of OH2

Hello,
when I startup OpenHab2 I often have “timing” problems, e.g. defaults don’t get set.
Example:
in my rules file on top:

var long Heizkreispumpe_start = now.millis
var long Heizkreis_Pumpe_heute = 0

Then further down:
rule "Umwalzpumpe OnTime Display update"
when
Time cron "0 0/1 * 1/1 * ? *"
then
if (Heiz_Umwalzpumpe.state == ON && Heiz_Kreislauf.state == ON) { // Pumpe ist an
val long nowMsec = now.millis
Heizkreis_Pumpe_heute = Heizkreis_Pumpe_heute + (nowMsec - Heizkreispumpe_start)
Heizkreispumpe_start = now.millis
Heizkreis_Pumpe_Heute_hours.postUpdate ( (Heizkreis_Pumpe_heute / 3600000.0).doubleValue)
}
end

Then I get:
Error during the execution of rule Umwalzpumpe OnTime Display update: An error occured during the script execution: Could not invoke method: org.eclipse.xtext.xbase.lib.LongExtensions.operator_minus(long,long) on instance: null

So I think, Heizkreispumpe_start is not initialized. But this does not happen all the time, only sometimes.
There are more situations like this, it’s only one example.

Is it a coding problem?
Or is there a way to “serilize” the start of OpenHab2, so the initialisation gets done?

Not as such. It just so happens that your rule is loaded in memory but not completely loaded when your cron expression goes off.

Nope, it happens in separate threads and is therefore non-deterministic.

What you can do is:

  • move your vals to Number Items and use persistence with restoreOnStartup instead of vars. Persistence and Items get loaded before rules so these Items will be initialized. Also, they will maintain their last values so your calculations will be able to take into account OH down time.

  • add a Thread::sleep at the start of the rule and sleep long enough for the vars to be fully initialized before running the rule.

  • change the rule to operate based on events (e.g. trigger when Heiz_Umwalzpumpe or Heiz_Kreislauf change state) rather than constant polling.

Thanks!!!
Will try your recomendations.

I’m a little bit closer to the problem. The declaration of the global variable in combination with setting it to “now.millis” does not work. Obviously, now.millis is not existing on startup. It takes some time. As a workaround I don’t initialize the global variable now, just declare it. Then there is a startup rule which set the variable on now.millis if it’s null.
Licht_Carport_start=if(Licht_Carport_start==null) now.millis else (Licht_Carport_start=Licht_Carport_start)
Thanks Rich.