How to Run a Cron Job
Cron is a Unix and Solaris utility that allows tasks to be run automatically. In other words, cron jobs allow you to automate certain commands or scripts on your server to complete repetitive tasks automatically. A cron job allows you to run a certain command at times set by the job.
For example, you could set a cron job to delete temporary files every week so that your disk space is not being used up by those files.
On Windows, this is equivalent to the Scheduled Task via the GUI. On Linux, the process is a bit more intimidating especially if you are not familiar with the syntax.
Crontab (CRON TABle) is a file which contains the schedule of cron entries to be run and at certain times.
Usually you would run the cron job as root or a user with permission to run the specified file. The tricky part about cron job is specifying the date and time when it should run.
You can use any editor to edit the crontab file. Typically you would use vi. To specify a default editor to use for the crontab editor, specify:
Afterwards, you can use these commands to perform on the command line:
crontab -e <— Edit your crontab file or create a new one if it doesn’t exist.
crontab -l <— Display your crontab file.
crontab -r <— Remove your crontab file.
A crontab has five fields for specifying day, date, time, and the command to be run at that interval.
When you are adding or modifying a cron job, you need to specify the date and time when the specified file should run. Notice that the format is
Minute (0-59) – Hour (0-23) – Day of Month (1-31) – Month (1-12) – Day of Week (0-6)
Day of Week starts on Sunday (0) and ends on Saturday (6).
The following examples should hopefully give you enough information for you to set a cron job without any problem.
Run every 5 minutes.
||Day of Week
Run hourly at 30 minutes past the hour.
30 * * * * /hourly.sh
Run every Friday night at 8:30 PM.
30 20 * * 5 /friday.sh
Run every night at midnight.
0 0 * * * /midnight.sh
Run every 4 hours.
0 */4 * * * /fourhour.sh
Run on the 15th of of every month at 12:15, 12:30 and every Monday morning.
30,15 0 15 * 1 /complex.sh
By default, the cron job sends an email to the user account running the cron job. If this is not needed, you can add the following to the end of the command you are running.
30,15 0 15 * 1 /some/path/complex.sh > /dev/null 2>&1
Create a Log File
When you run a cron job, it is always a good idea to create a log file. That way, you can view the output of what you ran or if you encounter any problems, you can see the error messages. To add a log file, add the following to the end of the cron job.
30,15 0 15 * 1 /some/path/complex.sh > /some/path/logs/cronjob.log
Incoming search terms:
- cron job 8:30 pm