What is CRON? Unix-like operating systems provide utility for run periodical tasks. For example you need to run script every day at 08:00 AM. CRON read tasks from configuration file line by line and have special syntax.
Windows have their own tool named as "Windows Task Scheduler".
Open terminal and run crontab -e
command. When you open crontab first time, you must choose editor, which is convenient for your use. Enter number of preferred editor and press "Enter":
user@localhost:~$ crontab -e
no crontab for user - using an empty one
Select an editor. To change later, run 'select-editor'.
1. /bin/nano <---- easiest
2. /usr/bin/vim.tiny
Choose 1-2 [1]:
When you open cron system display generated configuration file with description:
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
Structure of executable command:
# ┌───────────── minute (0–59)
# │ ┌───────────── hour (0–23)
# │ │ ┌───────────── day of the month (1–31)
# │ │ │ ┌───────────── month (1–12)
# │ │ │ │ ┌───────────── day of the week (0–6) (Sunday to Saturday;
# │ │ │ │ │ 7 is also Sunday on some systems)
# │ │ │ │ │
# │ │ │ │ │
# * * * * * <command to execute>
Here cheat-sheet of some examples:
Run task every minute:
* * * * * cd /home/user && ./my_script.sh
Run task every 5 minutes:
*/5 * * * * cd /home/user && ./my_script.sh
Run task every 1 hour:
0 * * * * cd /home/user && ./my_script.sh
Or use @hourly
definition.
Run task every day at 00:00:
0 0 * * * cd /home/user && ./my_script.sh
Or use @daily
definition.
If your command not running by any reason use bash -c
:
*/5 * * * * bash -c 'cd /home/user && ./my_script.sh'
Run task at system startup:
@reboot cd /home/user && ./my_script.sh
Save changes and exit from editor. Now we're need to reload CRON service. Its need for read configuration file again. Just use service cron reload
command:
user@localhost:~$ service cron reload
Reloading configuration files for periodic command scheduler: cron.
Top comments (0)