Monday, August 19, 2013

Run a cronjob to schedule tasks on Linux using crontab and url

If you’ve got a website that’s heavy on your web server, you might want to run some processes like generating thumbnails or enriching data in the background. This way it can not interfere with the user interface. Linux has a great program for this called cron. It allows tasks to be automatically run in the background at regular intervals. You could also use it to automatically create backups, synchronize files, schedule updates, and much more. Welcome to the wonderful world of crontab.

Cron is a daemon that executes scheduled commands. Crontab is the program used to install, deinstall or list the tables used to drive the cron daemon. The crontab (cron stands for time (Greek); tab stands for table) command, found in Unix and Unix-like operating systems, is used to schedule commands to be executed periodically. To see what crontab are currently running on your system, you can open a terminal and run:
crontab -l
To edit the list of cronjobs you can run:
crontab -e
This will open a the default editor to let us manipulate the crontab. If you save and exit the editor, all your cronjobs are saved into crontab. Cronjobs are written in the following format:
* * * * * /bin/execute/this/
Scheduling explained
As you can see there are 5 stars. The stars represent different date parts in the following order:
1. minute (from 0 to 59)
2. hour (from 0 to 23)
3. day of month (from 1 to 31)
4. month (from 1 to 12)
5. day of week (from 0 to 6) (0=Sunday)
Special words
Instead of the first five fields, you can also put in a keyword as follows:
@reboot     Run once, at startup
@yearly     Run once  a year     "0 0 1 1 *"
@annually   (same as  @yearly)
@monthly    Run once  a month    "0 0 1 * *"
@weekly     Run once  a week     "0 0 * * 0"
@daily      Run once  a day      "0 0 * * *"
@midnight   (same as  @daily)
@hourly     Run once  an hour    "0 * * * *"
Pratical examples on how to run CRON command using URL address
//CRON command to run URL address every hour
@hourly wget -q -O /dev/null ""

//CRON command to run URL address every midnight 
0 0 * * * wget -q -O /dev/null ""
You can use following crontab command also to run a task
* * * * * wget -O - >/dev/null 2>&1
Using -O - means that the output of the web request will be sent to STDOUT (standard output). By adding >/dev/null we instruct standard output to be redirect to a black hole. by adding 2>&1 we instruct STDERR (errors) to also be sent to STDOUT, and thus all output will be sent to a blackhole. (so it will load the website, but never write a file anywhere).

Ref: and

No comments:

Post a Comment