1. Home
  2. cPanel/WHM
  3. How do I set up cron jobs?

How do I set up cron jobs?

Den här artikeln finns även på svSvenska

Via cPanel, you can find the cron settings via the icon Cron Jobs under Advanced.

Choose when the cron job should be run and enter the Command you wish to run, then click Add New Cron Job.

You have to enter the command in the following fashion:

/path/to/program /home/yourusername/path_to_script > /dev/null 2>&1

For example, if you want to run a php script, the command could look like this:

/usr/local/bin/php /home/yourusername/script.php > /dev/null 2>&1

Managing output

If you wish, you can choose that an email should be sent to you after each cron job run. This can be practical if you want to see whether or not the job completed successfully. It may also help you troubleshoot a cron job that is not functioning as expected – the mail may then contain helpful error messages. If you want to receive those emails, you have to remove “> /dev/null 2>&1” from the cron job command:

/usr/local/bin/php /home/yourusername/path_to_script.php

You can select the receiving email address in the Email field just above where you set the time for your cron job.

Please note! If you want to run wget via cron and don’t wish any output, you must set both the -o and -O flags to /dev/null, for example:

wget -O /dev/null -o /dev/null "https://www.exempel.se"

Overlapping cron jobs

A problem that may arise when running cron jobs is that you don’t know exactly how long each run of the command will take. If you have a command that runs every five minutes and finishes in three, all is fine; but if you have a command that runs every five minutes and requires seven minutes to finish you run into trouble. In practicality, this will result in multiple cron jobs running at once – something you want to avoid.

There is, however, a solution: Flock. Flock creates a lock file when the cron job starts, and if the file still exists the next time the cron job is supposed to start, it won’t. When the cron job that created the lock file is done, the file is removed automatically.

You can use Flock in the following way:

/usr/bin/flock -w 1 /tmp/cron.lock /usr/local/bin/php -q /home/yourusername/path_to_script.php

/usr/bin/flock is the path to the Flock binary, and /tmp/cron.lock the path to the lock file – you do not have to edit those. You enter the rest of the cron job command after the lock file path, as described above.

Was this article helpful?

Related Articles