"Cron is a time-based job scheduler in Unix-like computer operating systems." -- From Wikipedia
To run scripts periodically, first you will need to create your own crontab file that states at what time do you want what program to run , which you can use
crontab -e to begin editing your crontab file.
After entering the editing mode, you might see a file similar to the following layout:
# 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/ #
To add task, you will need to append the following line to this file
# `minute` specifies at what minute you want your SCRIPT to be executed # `hour` specifies at what hour you want your SCRIPT to be executed # The same follow for `day_of_month` `month` and `day_of_week` # You can also use `*` to specify `any`, meaning that time feature will not be used for scheduling mintue hour day_of_month month day_of_week SCRIPT
However, cron cannot immediately execute iteself, meaning that if you want to debug your script under cron environment, you will need to manually update the time schedule every time you want to debug your script.
Also, note that cron has minimal environment so you won't have ANY environment variable availiable and you cannot use
source ~/.bashrc or
source ~/.profile because they will exit when the shell is not interactive.
Instead, you will need to create separate profile that manage env var you want, similar to:
# This file is $HOME/.cron_profile export VAR1=value1 export VAR2=value2
And your crontab file will be:
[Time schedule] source $HOME/.cron_profile; YOUR_SCRIPT
Cover Photo by Émile Perron