Let’s say you have a script that downloads live stock reports but it has to be during market hours only. It has to be only during Monday-Friday, and between market open at 8:30 a.m. and market close at 3:00 p.m. During these hours and days, we want to run the update script every three minutes. Based on the API limits of the stock data provider, it is critical that the script be called only during these dates and times.
Here is the rule to be run with the exec binding:
rule "StockUpdate"
when
Time cron "0 0/3 * * * ?"
then
if (now.getDayOfWeek <= 5){
if (new LocalTime().getLocalMillis() >= new LocalTime(08, 28, 0, 0).getLocalMillis()) {
if (new LocalTime().getLocalMillis() <= new LocalTime(15, 10, 0, 0).getLocalMillis()) {
executeCommandLine("/etc/openhab2/scripts/markets2.sh")
logInfo("stocks", "completed bash script test.")
}
}
}
end
Now let’s examine the above script. The trigger is cron which is set to check rule conditions every three minutes.
We are then going to do a series of nested if statements, all of which must be true to get to our actual script execution.
First, we need to make sure it is a weekday. So as long as the day of the week is not 6 or 7, then we are ok.
Next, we want to start running by 8:30 each morning, so we will set to start at 8:28 each weekday.
Next, we want to stop shortly after the close. It takes five to ten minutes for final prices to settle, so we will use 15:10 in military time.
If all these conditions are met, the script executes! While it may be possible to approximate this using only cron, this approach is far more accurate, easier to do, and more elegant.