Task Scheduling in Linux

Crontab screen shot

Recently, I was working on a dashboard project for visualizing COVID-19 situation in Nepal. This task required me to execute a python script to fetch data from the server, that too in an interval of a day. However, I was not able to figure out how this can be realized. After doing bit of googling and searching for the solution, I got linked with a Linux utility knows as cron (corn job). Just before it got out of my head I decided to make a note of it so that I can refer back to it whenever needed.

Corn is a tool that provides user with the feature to schedule a task based on time over a Linux platform (Wikipedia). Basically, once installed a corn daemon runs some process (with predefined scripts on cron tables) at a schedule time on the background. We will examine a way to schedule execution of a simple script on a Ubuntu system but before that let’s get some idea on crontab.

Crontab

A crontab (cron table) is simply a file that contains a list of commands or scripts scheduled to be run at the specified time. Once the command are set, cron daemon checks those task and executes them on the background.

What does it contain?

Corntab basically contains lines of comment and commands with defined schedule. It can be edited using crontab -e as below.

# edit crontab (requires sudo privilege)
sudo crontab -e

Above command should open on default terminal editor and shows the list of scheduled jobs for the cron daemon. Typical job would be in the following format.

# comment
a b c d e f /path/command
  • First line
    • text followed by # is a comment that describes the job
  • On the second line:
    • a b c d e – represents date and time field, where
      • a – minute (0-59),
      • b – hour (0-23, 0 = midnight),
      • c – day (1-31),
      • d – month (1-12),
      • e – weekday (0-6, 0 = Sunday)
    • /path/command – represents command to be executed

Examples

  • Run script at 00:00 am every month on 15th calender’s day. * represents all value.
0 0 15 * * /bin/bash ${HOME}/scripts/sys_diagnosis.sh
  • Run scripts at 7:30 am every day
30 7 * * * /bin/bash ${HOME}/scripts/sys_diagnosis.sh
  • Run scripts every 30 minutes on weekend. */30 represents every 30 minutes, and 0,6 represent Sun. and Sat.
*/30 * * * 0,6 /bin/bash ${HOME}/scripts/sys_diagnosis.sh
  • Run scripts every 5 hours from Mon-Friday.1-23/5 represents every 5 hours and 1-5 represents Mon. to Friday.
0 1-23/5 * * 1-5 /bin/bash ${HOME}/scripts/sys_diagnosis.sh