April 21, 2024

Impact & Learning

Learn to impact

Task automation in Linux with Crontab

Task and processes automation in Linux with Crontab is essential for every developer and architect. When we talk about the need to run a task or a script every certain time interval and avoid depending on a user action, or if we need to run it on a certain day, hour and minute, we have reached a good point to know the advantages of running a scheduled task through a cronjob.

Crontab is a software utility for scheduling or scheduling tasks, which in use is similar to the Windows task scheduler, with the additional advantage of allowing tasks to be scheduled at defined times or intervals in a very simple way.

Accessing the crontab file

To add an automated task, it is necessary to define it in a file that crontab will read, which according to the Linux distribution we have is located in one of the following routes:

/var/spool/cron -> For Red Hat based distributions (Fedora, CentOS, etc.)
/var/spool/cron/crontabs -> For distributions based on Debian and Ubuntu.

However, according to the existing user, we can automate tasks. Therefore, it is recommended that the root user be used for these, to avoid problems with permissions as much as possible, accessing either through su or with sudo.

The easiest way to see the existing automated crontab tasks is through the –l option, where it shows the tasks waiting for the time signal for execution:

crontab -l

Which is similar to running: cat /var/spool/cron (Red Hat) or cat /var/spool/cron/crontabs (Debian).

To add, edit or delete a scheduled task, it is easy to access the configuration file with the -e option:

crontab -e

Which is similar to running: vi /var/spool/cron (Red Hat) or vi /var/spool/cron/crontabs (Debian).

Scheduled Task Settings

When opening the configuration file, the structure to follow for scheduling an automated task is as follows:

# Example of task definition
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of the month (1 - 31)
# | | | .------- month (1 - 12) O jan, feb, mar, apr ... (in English)
# | | | | .---- day of the week (0 - 6) (Sunday = 0 or 7) O sun, mon, tue, wed, thu, fri, sat
# | | | | |
  * * * * * username command_to_ run

For example, if we want to execute an example.sh task every day at 02:30 hours (am), we write it with its absolute path (as root user):

30 2 * * * /home/john/example.sh

Example 2: To run the example.sh task every 10 minutes, we write:

*/10 * * * * /home/john/example.sh

Example 3: Run the example.sh task every Saturday at 00:00

0 0 * * 6 /home/john/example.sh

Example 4: Execute the example.sh task on February 1st at 10:00 am

0 10 1 2 * /home/john/example.sh

Example 5: Run the example.sh task every minute

* * * * * /home/john/example.sh

If you want to calculate a custom time or lapse to execute a task, maybe you could find a tool to calculate the lapse, for example crontab.guru