Cron Jobs in Arduino



The CronAlarms library in Arduino helps you set cron jobs in Arduino. If you aren't aware of cron jobs, they are scheduled tasks to be carried out at a fixed time interval. An example can be sending a health packet to a server every day at midnight.

In order to install this library, search for CronAlarms in the Library Manager and install the library by Martin Laclaustra.

Once installed, go to - File → Examples → CronAlarms.

Open CronAlarms_example. If you go through the example, you will see that they are doing the following −

  • Set the time to Saturday 8:29:00am Jan 1 2011, using the tm struct (time library)

  • Sets 6 Cron alarms, daily, weekly, at interval of few seconds, and even a one-time triggered non-repeating alarm.

  • The one-time triggered non-repeating alarm, in fact, disables the 2-second cron.

  • Within the loop, the current time is printed every second.

The cron creation syntax is -

CronID_t create(const char * cronstring, OnTick_t onTickHandler, bool isOneShot);

Where

  • cronstring provides the cron interval,

  • onTickHandler is the function that will be called when the alarm is triggered,

  • isOneShot determines if the alarm is repeating or is a one-time interval.

This function returns a cron ID, which can be used to reference the alarm elsewhere in the code, as is done in the 10-second alarm, to disable the 2-second alarm, using Cron.free().

//creating the 2-second repeating alarm and 10-second single-shot alarm

// timer for every 2 seconds
id = Cron.create("*/2 * * * * *", Repeats2, false);

// called once after 10 seconds
Cron.create("*/10 * * * * *", OnceOnly, true);

// 2-second alarm function
void Repeats2() {
   Serial.println("2 second timer");
}

//disabling 2-second alarm within the 10-second alarm
void OnceOnly() {
   Serial.println("This timer only triggers once, stop the 2 second timer");
   // use Cron.free(id) to disable a timer and recycle its memory.
   Cron.free(id);
   // optional, but safest to "forget" the ID after memory recycled
   id = dtINVALID_ALARM_ID;
   // you can also use Cron.disable() to turn the timer off, but keep
   // it in memory, to turn back on later with Alarm.enable().
}

The most important part of creating the CronAlarm is the cron string. Its syntax is −

"seconds minutes hours days_of_month month days_of_week"

A * for any of these means 'all values'. Thus,

  • "0 30 8 * * *" → Indicates trigger at 8:30:00 every day.

  • "30 30 8 * * 6" → Indicates 8:30 trigger at 8:30:30 every Saturday (day_of_week = 6)

  • A / in the expression indicates interval.

  • "*/15 * * * * *" → Indicates every 15 seconds.

If you run this example on your Arduino, the Serial Monitor output will be −

As you can see, the alarms get triggered as expected.


Advertisements