Setting up cron jobs on linux via command line

Cron jobs allow you to run scheduled tasks on your server, which can be really useful if you need to back up, clear or sort data on a regular basis. In this tutorial we're going to look at setting up a simple cron job via command line that will call a designated url each day.

Creating a cron job

Firstly you need to decide how frequently you want your job to run and then generate the correct text that we'll add to your cron table. You can use a crontab gode generator to do this or manually if you understand the simple configuration:

MINS    HOURS    DAYS    MONTHS    WEEKDAYS    all tab delimited. So for example:


5 0 * * *

...will run at 5 minutes past midnight every day.

With this information, follow the steps below to add a cron job:

  • Login to your server and run crontab:

    crontab -e

    This will open a list of cron jobs running for this user in '-e' edit mode. Press 'a' to go into append mode.

  • Add your crontab along with the command to run, in this example we're going to load a URL

    5 0 * * * lynx -dump http://yoururl.com

    Note lynx is a command line web browser (to check if it is installed simply type lynx at the command line). The dump argument tells the browser to dump the content to the standard output rather than opening the url in interactive mode.

  • If you wanted to run a PHP file directly on the server instead of opening it via a browser you could also do:

    5 0 * * * /path/to/php /path/to/script.php
  • Type :write to save the file.
  • Type :quit to close the file.
    (note steps 3 and 4 will depend on your server, see the commands available)

...and you're done. If you want to run a test, try changing it to every minute (all astrisks) and writing the update to a log, here's an example file to place in your public directory that the cron job would call (don't forget to create the cronLog.txt file first!):

$file './cronLog.txt';
$current file_get_contents($file);
$current .= "File updated at " . date('d-m-y h:i:s', time()) . " \n";
file_put_contents($file$current);

Sign Up
comments powered by Disqus
Sign Up

Popular Tags

350x250

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.