Configurable rule that has the cron specification parameterized

  • Platform information:

    • Hardware: RPI3B
    • OS: OPENHABIAN
    • openHAB version: openHAB 2.5.10-1
  • Issue of the topic:

    Hello,
    Please let me know how I can use a variable inside a CRON expresion. I want to have the option to configure the starting time and ending time from the user interface perspective.
    So, for example a have this rule:

rule “All lamps on”
when Time cron “0 0 6 ? * MON-FRI *”
then all_lights_on_on.sendCommand(“ON”)
logInfo(“info”,“all lights on rule fired”)
end

And I want to modify the value 6 - (rule to be considered from 6 AM).

Until now I found this post / solution that is from '15. Maybe do you know other approach / workaround:

Thank you in advance

You cannot.

Thank you for prompt answer!

With the Jruby scripting addon, you can!
dynamic_rule.tems:

String Cron_Expr "Cron expression for dynamic rule"

dynamic_rule.rb

require 'openhab'

def dynamic_rule(name, cron_expr, &block)
  remove_rule(name)
  rule name do
    cron cron_expr
    run block
  end
end

def remove_rule(name)
  rules = $se.get('ruleRegistry')
  rules.get_all.select { |rule| rule.name.match?(name) }.each { |rule| rules.remove(rule.uid) }
end

rule 'Update cron rule' do
  changed Cron_Expr
  run do
    dynamic_rule('Dynamic cron rule', Cron_Expr) do
      # Rule body here
    end
  end
end

Update the Cron_Expr Item with a valid cron expression and the rule will be recreated with the new value.
Just make sure you use unique names for your rules, otherwise you might delete the wrong one.

1 Like

This is brilliant!

1 Like