Crontab is an important utility that is used for scheduling cron jobs i.e. setting up a specified time-based job. Cron job can be a single command or we can also schedule cron to run bash scripts.
These cron jobs help us automate repetitive tasks like backups, system updation, or running some specific command or scripts, etc. We can schedule cron jobs & the system will then execute the mentioned commands or scripts without human intervention. Cron jobs can be scheduled to run on the minute, hour, day of the month, month, day of the week basis. We can also combine any of these to schedule cron jobs.
Recommended Read: Beginner’s guide to Backup Postgres Database
Also Read: How to setup SSH login without password on Linux systems
Scheduling Cron jobs
Syntax:- We need to provide the cron job in the following format,
(minute) (hour) (day of the month) (month) (day of the week) (command/script path)
* * * * * command, script(s) - - - - - | | | | | | | | | ------ Day of the week (0 - 7) (Sunday=0 or 7) | | | ------- Month (1 - 12) | | -------- Day of the month (1 - 31) | ---------- Hour (0 - 23) ------------ Minute (0 - 59)
Commands to list, delete or schedule cron jobs are mentioned below,
-> Schedule cron job or edit a job,
To edit or create a cronjob, run
$ crontab –e
-> Display all cronjobs
$ crontab –l
-> Removing a cronjobs
$ crontab –r
Or we can just edit out a job that we don’t want need with ‘crontab -e’ command.
-> Using crontab for other users
$ crontab -u test_user -e
$ crontab -u test_user -l
$ crontab -u test_user -r
Here, you can replace ‘test_user’ with the username you need to see access cron jobs for. The root user will access to cron jobs for all users by default.
Examples of scheduling cron jobs
1- Running a backup script named backup.sh located at /home/test_user everynight at 10:00PM,
00 22 * * * /etc/test_user/backup.sh
2- Running a weekly backup script named weekly_backup.sh on every Friday at 10:30,
30 23 * * 5 /etc/test_user/weekly_backup.sh
3- Running a monthly backup script named monthly_backup.sh on 30th day of every month at 11:45PM,
45 11 30 * * /etc/test_user/monthly_backup.sh
4- Running backup script named weekday_backup.sh on weekdays only at 11:59 PM
59 11 * * *1-5 /etc/test_user/weekday_backup.sh
or
59 11 * * *1 2 3 4 5 /etc/test_user/weekday_backup.sh
We can also run a script on selective days, like odd days,
59 11 * * *1 3 5 7 /etc/test_user/weekday_backup.sh
5- Running a command every 10 minutes,
* /10 * * * command
These were only some examples of how you can use cron jobs, there are plenty more combinations we can use. We now end our tutorial on scheduling cron jobs on the Linux system. Please feel free to send in any questions or queries you have using the comment box below.