Ever need to complete the same mundane task on a daily basis? If so, Cron is for you! Cron can make your life easier by scheduling those mundane tasks to be ran automatically. Cron is a daemon and runs in the background of basically every Linux based system.
Update: Continuing our journey into the magical world of open source software I would like to expand on my home security tutorial. A wonderful person by the name of Morgan Storey has made a few scripts available, to automate the mundane process of activating motion when you leave and help clean up after Motion. Here are the scripts if you would like to use them.
Step One: How to configure cron?
To start off the configuration file for cron is call crontab. This is where the cron daemon checks to see what needs to be done, to check if crond (cron daemon) is running type ps aux | grep crond into the terminal. Check if crond is returned in the results, if not you can start cron by adding the line crond to one of your start up scripts.
Now lets create our first scheduled task. Start off by typing crontab -e into terminal, please note I’m using nano as the default text editor on my system.
Here is an ASCII repartition of how the scheduling system works in cron. The command is stated at the right of the time to be executed.
# +---------------- minute (0 - 59) # | +------------- hour (0 - 23) # | | +---------- day of month (1 - 31) # | | | +------- month (1 - 12) # | | | | +---- day of week (0 - 6) (Sunday=0 or 7) # | | | | | * * * * * command to be executed
For example if you want an entry to be executed at 12PM every monday you would;
0 12 * * 1 /command_directory/executed_command
Each line represents a seperate crontab entry.
The asterisk (*) is a wild-card meaning I want the entry above to be executed no matter the day or month.
Step Two: How to create a shell script?
To make cron, even more, useful you should know how to create a shell script (groups of commands).
A shell script is basically a group of commands that work together towards a common goal. Lets say we wanted to make a script that deletes the contents of a few folders. We would make the script look similar to this;
#!/bin/bash# Simple folder deleterm ~/samplefolder/*rm ~/samplefolder2/*echo "Folders deleted!"
A shell script can even execute multiple commands at the same time by using a double ampersand (&). For example;
#!/bin/bash# Simple folder deleterm ~/samplefolder/* && rm ~/samplefolder2/*echo "Folders deleted!"
For more information on creating shell scripts there is a very nice tutorial on the Ubuntu Forums; here.