Rule is executed slow

I created already several rules which are working ok.
But my latest rule, gets executed 30-40 seconds after the trigger took place…

Rule

import org.openhab.core.library.types.DecimalType

var diameter = 20 // cm
var hoogte = 25 // cm
var Number measure_cm
var Number waterpeil
var Number inhoudTon
var Number inhoud
var Number inhoudPerc

rule “calculate water content”
when
Item MQTT_distance changed
then
logInfo(“regenton”, “executing rule”)

measure_cm = (MQTT_distance.state as DecimalType) / 10
inhoudTon = (3.14 * ((diameter / 2) * (diameter / 2)) * hoogte) / 1000
waterpeil = hoogte - (measure_cm)
inhoud = (3.14 * ((diameter / 2) * (diameter / 2)) * waterpeil) / 1000
inhoudPerc = (inhoud / inhoudTon) * 100

logInfo("regenton", "inhoud: " + inhoudTon + " liter")
logInfo("regenton", "waterpeil: " + waterpeil + " cm")
logInfo("regenton", "inhoud NU: " + inhoud + " liter")
logInfo("regenton", "inhoud NU: " + inhoudPerc + " %")

MQTT_water_content_full.postUpdate(inhoudTon)
MQTT_distance_cm.postUpdate(measure_cm)
MQTT_waterpeil.postUpdate(waterpeil)
MQTT_water_content_current.postUpdate(inhoud)
MQTT_water_content_current_perc.postUpdate(inhoudPerc)

end

log:

2017-08-15 20:26:38.710 [ItemStateChangedEvent ] - MQTT_distance changed from 176 to 32
2017-08-15 20:27:19.737 [INFO ] [ipse.smarthome.model.script.regenton] - executing rule
2017-08-15 20:27:19.905 [INFO ] [ipse.smarthome.model.script.regenton] - inhoud: 7.85 liter
2017-08-15 20:27:19.910 [INFO ] [ipse.smarthome.model.script.regenton] - waterpeil: 21.80000000 cm
2017-08-15 20:27:19.916 [INFO ] [ipse.smarthome.model.script.regenton] - inhoud NU: 6.8452 liter
2017-08-15 20:27:19.924 [INFO ] [ipse.smarthome.model.script.regenton] - inhoud NU: 87.20000000 %

When I remove the formulas, the rule is executed immediately… the formulas aren’t that difficult :slight_smile:
Are there maybe better ays to do these kind of things?

Pi and sqrt are also not working with import java.lang.Math.*

First, imports must not contain a * (since OH2.0)

I don’t know why the formula takes so long, but maybe you can avoid this behavior as the main part is a constant value, so try to set this value outside the rules:

val Float flat = 3.14 * diameter * diameter / 4000
val Number inhoudTon = flat * hoogte

and then within the rule:

inhoud = flat * waterpeil

maybe this speeds up the rule.

flat and inhoudTon are constants and only calculated when the rule file is updated or changed (or in case of restart openHAB)

Thanks for the help, your code is a little bit better :slight_smile:
The strange thing is that when I tried my old code yesterday, it was executing immediately…

To use pi and sqrt, do It need to import them both? Because In tried this, but they were not recognized…