WordPress Cron

ClockWordPress needs a cron to work. By default, a function wp_cron is executed each time a visitor loads a page from your website. If there is a job to execute, it does it at this time.

This is not ideal

  • if you have low traffic, tasks could be executed after the time planned
  • if you have heavy traffic, performances can be affected by this function run on each page
  • globally speaking, I prefer not having jobs not related to http depending on Apache

To avoid that, we can do 2 operations

  • disable wp_cron
  • create a “real” cron task on our server

Disable wp_cron

This is very simple, just edit wp-config.php and add the line (below the header comments of the file for example)

If you host several WordPress, you can put this line in every wp_config.php

Setup a real cron task on your server

The job to execute is simply

so if your website is stored in /var/www/

To setup it on cron to execute every 5 minutes

(the www-data is to execute the job with the context and the rights of Apache user, www-data on Ubuntu)

Bonus for multiple virtual hosts

If you several WordPress websites hosted on the same server, you will perhaps want to run the cron for all instances in one command.

This command is looking for all the files named wp-cron.php in /var and subdirectories at the second level. For each occurence, it executes php on it.

One more thing

When playing with crons, you need to always ask the question “what if multiple intances of the same job are running” ?

To be more precise, if you setup the cron job to run every minute, what if the job takes more than 1 minute to execute ?

Franckly, I do not know if and how WordPress handle this but here is the command enabling a lock on the execution

flock puts a lock file “/tmp/wp-cron.lock” and executes the command after -c.

When the command is finished, the lock file is suppressed.
-x tells that this is an exclusive lock
-n tells that the second execution does not have to wait, just stop

If a second task is launched before the first beeing finished, the second one will just cancel.

So my cron is :

Great, isn’t it ?