Sample Crontab to Schedule Tasks
If we have task that need to be executed periodically, then crontab can help us. Crontab is a very useful to run unattended scheduled tasks. The crontab file defines what is to be done and when. It consists of lines of text. Completely blank lines or lines starting with ‘#’ are ignored.
Here is an example of crontab file entry:
30 23 * * * sh /root/backup.sh
In the crontab file, there are six fields for each entry, each field separated by spaces or tabs. The first five fields specify when the command will be run. The sixth field is the command itself.
Minute - 0-59.
Hour - 0-23 24-hour format.
Day - 1-31 Day of the month.
Month - 1-12 Month of the year.
Weekday - 0-6 Day of the week. 0 refers to Sunday.
# min(0-59) hours(0-23) day(1-31) month(1-12) dow(0-6) command 30 23 * * * sh /root/backup.sh
Here are commands related to crontab:
- crontab -e – Edits the current crontab, or creates a new one.
- crontab -l – Lists the contents of the crontab file.
- crontab -r – Removes the crontab file.
- crontab -u – Edits user’s crontab.
To create a scheduled task using cron, execute crontab -e to open the editor and write the crontab file.
Here are some examples of crontab file entry.
1. To schedule a backup script to run every day at 23:30
30 23 * * * sh /root/backup.sh
2. This crontab entry will run the backup script daily at midnight:
@daily sh /root/backup.sh
3. To run a command every 10, 20, and 30 minutes after every hour, during the month of October, the entry would be:
10,20,30 * * 10 * /usr/bin/command
4. To run a backup script on just Monday trough Friday at 23:30, the entry would be:
30 23 * * 1-5 sh /root/backup.sh
5. To run a script every two hours, the entry would be:
0 */2 * * * sh /root/script.sh
6. To run a script at 15 minutes after every 4th hour of every day, the entry would be:
15 */4 * * * sh /root/script.sh
7. To run a script at date 10th every June – July at 23:30, the entry would be:
30 23 10 6-7 * sh /root/script.sh
8. To get cron to write the output of the commands to a log, the entry would be:
15 */4 * * * sh /root/script.sh >> /root/script.log 2>&1
9. To have cron suppress the e-mail report:
15 */4 * * * sh /root/script.sh > /dev/null 2>&1