Linux cron jobs explained with WordPress maintenance task examples

Linux cron jobs for WordPress maintenance

WP-Cron runs scheduled tasks when someone opens a page. On a quiet site tasks run late; on a busy one the check runs on every request. A system cron job runs WP-Cron and the other maintenance commands at fixed times, whether visitors come or not.

Problem: Scheduled posts are published late, nightly cleanups do not run on weekends, and backups depend on someone remembering them.

Solution: Disable the page-load trigger with DISABLE_WP_CRON, run the due events every five minutes from the crontab of the site user with WP-CLI, and add the backup and cleanup commands as separate cron lines with logging and flock against overlapping runs.

Crontab syntax

# min  hour  day-of-month  month  day-of-week  command
  */5  *     *             *      *            every five minutes
  0    2     *             *      *            every day at 02:00
  0    3     *             *      0            Sundays at 03:00

Edit with crontab -e as the user that owns the WordPress files (often www-data: sudo crontab -u www-data -e), list with crontab -l. Running WP-CLI as root creates files that the web server cannot write later.

Disable the page-load trigger

// wp-config.php, above "That's all, stop editing!"
define( 'DISABLE_WP_CRON', true );

The crontab

MAILTO=""
PATH=/usr/local/bin:/usr/bin:/bin
WP="wp --path=/var/www/example --quiet"

*/5 * * * * flock -n /tmp/ha-wpcron.lock $WP cron event run --due-now >> /var/log/ha/wp-cron.log 2>&1
0   2 * * * flock -n /tmp/ha-backup.lock /var/www/bin/backup.sh >> /var/log/ha/backup.log 2>&1
30  3 * * * $WP transient delete --expired >> /var/log/ha/cleanup.log 2>&1

Cron starts with an almost empty environment: set PATH, always pass --path to WP-CLI and use absolute paths for scripts and logs. flock -n skips a run while the previous one still works, so a slow backup does not start twice. The log folder must exist and be writable for the cron user. A backup script is in automate WordPress backups with a Bash script.

Without WP-CLI

*/5 * * * * curl -s -o /dev/null "https://example.com/wp-cron.php?doing_wp_cron"

This goes through the web server and is limited by its timeouts; WP-CLI is better if it is installed.

Check that it runs

wp --path=/var/www/example cron event list
grep CRON /var/log/syslog | tail -n 5

In the event list, the “next run” times should be in the near future, not in the past. The syslog shows each start of a cron line.

NOTE: Keep the jobs that only clean up symptoms out of the crontab. A nightly restart of PHP-FPM or MySQL “to free memory” hides a leak or a misconfiguration and drops the requests that are running at that moment; find the cause with the server’s monitoring instead. More WP-CLI commands: essential WP-CLI commands.