If you are using Windows, you are probably familiar with task scheduler to schedule certain tasks automatically. With Linux, tasks can be done on scheduled dates with cron.
cron is the service that works like task scheduler in Windows and can be used if you want to automate repetitive tasks like generating reports everyday or virus scanning. cron is handled by the cron daemon or crond, which should be running if you want your scheduled tasks to run.
Scheduling cron jobs are very simple. You just need to understand one teeny weeny line that comes with scheduling jobs. If you will take a peek at one of the cron files that exists by default on Linux systems, such as /etc/crontab, you will something like this:
01 * * * * root nice -n 19 run-parts /etc/cron.hourly
02 4 * * * root nice -n 19 run-parts /etc/cron.daily
22 4 * * 0 root nice -n 19 run-parts /etc/cron.weekly
42 4 1 * * root nice -n 19 run-parts /etc/cron.monthly
Now don’t get scared, it won’t bite. At least for now. Anyway, these lines are simple to understand and here is a breakdown:
Column 1: Tells the minute part of the schedule. (Values are 0-59)
Column 2: Tells the hour part of the schedule. (Values are 0-23)
Column 3: Tells the day of month part of the schedule. (Values are 1 -31)
Column 4: Tells the month part of the schedule. (Values are 1-12)
Column 5: Tells the day of the week part of the schedule. (Values are 0-7, 0 is Sunday)
Column 6: Tells which user will execute the command.
Column 7: Tells the command that will be run.
So, a simple task that we could run to test our cronjob is to to create a test file and update its timestamp everytime the scheduler runs. We could do it like this:
30 15 * * * root touch /root/cron-test.txt
The ‘touch’ command will run once a day, every day at 3:30PM. What the command does is it will create a file if it doesn’t exist and will update its timestamp if it already does. This we will know if the task was executed if we see the file named as /root/cron-test.txt.
Once a day seems a little too long to wait so we should run the task every 15 minutes so we can see the timestamp updated by doing this:
*/15 * * * * root touch /root/cron-test.txt
This will run the task every 15 minutes for the rest of the day, everyday. If set to this, you should see the timestamp of /root/cron-test.txt updated every 15 minutes by doing ls -l command.
Of course you can do so much more with crond except updating timestamps on empty file. One good example is to create an archived backup of your home directory every day. However, this task could need a little bash script.