Running Commands on a Schedule
Scheduling commands to run at certain times using the cron daemon
cron is a daemon (a program that runs in the background) that you can use to schedule recurring tasks in Linux. You can run programs every N minutes, hours, or days; or even at certain times and on certain days of the week, and more.
To illustrate this Omega tip, we’ll schedule a GPIO to be set to high at 9am and then set to low at 5pm, every day. This is very similar to the cron setup in the IoT Lock project from the Omega2 Project Book.
Intro to cron
Cron commands are scheduled using a file called the crontab. To get started with cron, enter the following command on the command line from any directory:
If you’ve never before worked with cron, an empty file will show up. Each scheduled task in the crontab should follow the syntax below.
* * * * * (command to execute) (command arguments)
The 5 asterisks are placeholders for the following units of time:
- Minute (0 – 59)
- Hour (0 – 23)
- Day of month (1 – 31)
- Month (1 – 12)
- Day of week (0 – 7)
- (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
The asterisks mean “every”, but you can replace them with specific minutes, hours, days, etc. on which to run your program.
NOTE: The crontab file must end with a comment (just # is fine) in order for cron to run.
Adding to the Crontab
We can control the GPIOs with the gpioctl utility. Let’s edit the crontab by entering crontab -e and adding the following lines:
# 0 9 * * * gpioctl dirout-high 1 0 17 * * * gpioctl dirout-low 1 #
Hit Esc, then type :wq to save your changes and close the file.
Let’s break down the schedule parameters:
- 0 – On the 0th minute (:00)
- 9 – On the 9th hour (9:); same applies to 17
- * – On every day of the month
- * – On every month of the year
- * – On every day of the week
The command that follows is what will turn our GPIO on and off. The gpioctl command requires an action and a GPIO pin: gpioctl <action> <GPIO>. To turn the GPIO on, we use the dirout-high action, which will set the GPIO to the output direction and set the output to HIGH. Conversely, dirout-low will set the output to LOW.
Now restart cron to load your changes:
And that’s it! The Omega will run the everyday.sh script every day, setting GPIO 1 to high at 9 AM and low at 5 PM. You can also change the command section to run a Python or shell script instead.
For details and more examples of cron scheduling, head over to our Running a Command on a Schedule guide.
P.S. If your project is featured in 2-Bullet Tuesday, you will receive an Omega2+, a Dock of your choice, AND free shipping!
P.P.S. We’ve posted a video on YouTube showing how to set up an Omega2 the very first time. Let us know what other Omega2 topics we should make videos about!