Merikanto

一簫一劍平生意,負盡狂名十五年

Crontab in Linux

Many tasks in Linux are running day and night, regardless when people are asleep or not. So in order to run some processes automatically and periodically, we need to resort to Linux’s Crontab.


The crontab (cron derives from chronos, Greek for time; tab stands for table) command is used to schedule commands to be executed periodically. To see what crontabs are currently running on the system, we can open a terminal and run:

1
sudo crontab -l

To edit the list of jobs, we can run:

1
sudo crontab -e

If you want to add time to it, then use the command in this format:

1
* * * * * /command

A brief explanation of the * here (from left to right):

Explanation
1st * Minutes 0 - 59
2nd * Hours 1 - 23
3rd * Date 1 - 31
4th * Month 1 - 12
5th * Days 0 - 6 (Sunday is 0)

More Commands

To start the service manually (normally it’ll be on automatically):

1
sudo cron -f &

Here, & means to run processes in the background.

To start the log:

1
sudo service rsyslog start

To add new tasks (Below is an example):

1
*/1 * * * * touch /home/folder/$(date +\%Y-\%m-\%d)

*/1 means to execute the task every 1 minute,
The commands after the $ sign indicates the filename’s format. The line means to create a new file under that specific path every 1 minute.

Note that in Crontab, the escape character \ must be added before %, otherwise the default will be to switch to the next line.

To check Crontab’s status in the background:

1
ps aux | grep cron

To check feedbacks:

1
sudo tail -f /var/log/syslog

Here, tail -f means to get real-time feedbacks. This is particularly useful.