Schedule tasks with cron in Ubuntu

Sometimes, we have a task which needs to be run frequently at a specific time and day. If we don’t schedule the tasks then, we have to execute it manually. Although, at times it would be fine but what if we need to execute the task at odd hours or we can’t access the system at that particular time even remotely. There are so many other things which may act as hindrance. So, it would be great if we could schedule tasks. That way, we may divert useful resources to other productive work. In this article, we would cover one of the solution i.e. Schedule tasks with cron in Ubuntu.

There are mainly two types of tasks – system and user tasks. The system related tasks are handled by the superuser whereas the user tasks by a user.

We would like to add here that, /etc/crontab configuration file is for system-wide crontab. Just like the system-wide crontab, we also have user-specific crontab. User-specific crontab is executed by a user through crontab -e command, which we will discuss next.

Schedule tasks with cron in Ubuntu

First and foremost, the cron daemon reads the system crontabs and user-specific crontabs every minute. So, if we want the cron to execute a task then it would take a minute to read. Thereafter, it would execute the task.

To edit our crontab then, issue the following in terminal –

crontab -e

If we run the above for the first time, it would ask us to select an editor. Here, choose the editor you are most comfortable with.

Each entry here consists of six fields. It starts with minute (0-60), hour (0-23), day of month (1-31), month (1-12), day of the week (0-7) and lastly the command we intend to execute. This is how it should be –

* * * * *  command

The first * (asterisk) is for the minute, next for hour, day of month, month of year, day of week and at the last, its the command itself.

For instance, if we intend to execute a command every day in the noon ( at 1400 hrs) then, the entries would be –

0 14 * * * touch /dev/shm/test_file

We use * (asterisk) here for ‘any‘. Otherwise, provide the value as mentioned above according to minute, day etc.

To list our tasks, we can use the following command –

crontab -l

Lastly, if you want to remove all tasks at once from the crontab then –

crontab -r

Or, you may choose to remove the specific ones just by editing the file using crontab -e.

In conclusion, we have discussed how to schedule tasks with cron in Ubuntu.