Task Scheduling
This document covers the use of 'cron', 'crontab' and 'sh' in CoreELEC for a novice user in linux programming.
Preparation
Prior to scheduling a task:
- open an SSH terminal
- create a `scripts` directory
Creating the scripts directory in .config, allows the scripts to be saved with the CoreELEC backup.
mkdir /storage/.config/scripts
(change attributes)
chmod 775 /storage/.config/scripts
(create a link in 'storage' to be able to access the new scripts directory from kodi)
ln -s /storage/.config/scripts /storage/scripts
(remember that from now /storage/.config/scripts is the same as /storage/scripts)
- The scheduled tasks will be in shell files in the *scripts* directory.
Make script executable
chmod 755 /storage/scripts/backup.sh
Create Cron Job
To create a cron job, you’ll need to understand cron’s syntax and formatting first. Otherwise, correctly setting up cron jobs may not be possible.
Syntax
The crontab syntax consists of five fields with the following possible values:
# ┌───────────── minute (0 - 59) # │ ┌───────────── hour (0 - 23) # │ │ ┌───────────── day of the month (1 - 31) # │ │ │ ┌───────────── month (1 - 12) # │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday; # │ │ │ │ │ 7 is also Sunday on some systems) # │ │ │ │ │ # │ │ │ │ │ # * * * * * <command to execute>
Don’t leave any of the fields blank.
If, for example, you want to set up a cron job to run /storage/scripts/backup.sh
every Friday at 5:37 pm, here’s what your cron command should look like:
37 17 * * 5 /storage/scripts/backup.sh
In the example above, 37 and 17 represent 17:37 hours (5:37 pm). Both asterisks for the Day of the month and Month fields signify all possible values. This means that the task should be repeated no matter the date or the month. Finally, 5 represents Friday. The set of numbers is then followed by the location of the task itself.
If you’re not sure about manually writing the cron syntax, you can use free tools like Crontab Generator
Execution
- To execute any script we will use the sh command:
sh /storage/scripts/backup.sh
- To execute the scripts as scheduled tasks we will use the command:
crontab -e
Adding crontab
- and we will add lines as in the following example:
... 5 5 * * * sh /storage/scripts/backup.sh ...
(restart will run every day at 05:05 in the morning)
- You can use commas in crontab timers:
20 7 * * 1,5 /storage/.config/scripts/backup-and-reboot.sh 20 7 * * 2,4,6 systemctl reboot
Autostart Script
All of this is launched from /storage/.config/autostart.sh
with the command:
crontab /storage/.config/scripts/crontab.conf
Shutdown Script
Space reserved for shutdown.sh example