Site icon GetPageSpeed

WordPress Cron Optimization

Wordpress Cron

Wordpress Cron

WordPress has not only became a popular blogging platform in last years. It is now used for building complex enterprise websites. However, it has some weak performance spots by default. One of those spots is WordPress cron.

The default crontab runs using internal WordPress schedule. If there are no hits to your website, then crontab simply doesn’t run. If there is a hit and it happens that the user visited the site when cron has to run, their visit will be slow.

Fix WordPress Cron Performance

To make sure things run smoothly, we have to make WordPress cron tasks are launched by real Linux cron service.

We have to edit crontab as site’s user, not as root: crontab -e will launch crontab editing screen.

* * * * * /usr/bin/php /var/www/html/wp-cron.php

This crontab entry above will make sure that WordPress cron is run every minute.

If you want to have it run every other minute instead, use:

*/2 * * * * /usr/bin/php /var/www/html/wp-cron.php

Now all we have to do, is tell WordPress that it does not need to run cron tasks, because we have it handled by Linux system. Edit wp-config.php and put a line after opening php tag, like this:

<?php
define('DISABLE_WP_CRON', true);

Tap yourself on the back for making your website’s users happy. Their browsing experience is not affected by WordPress cron anymore. WordPress internal tasks will always run on time.

Filter some errors

If you were to disable error_reporting function like we recommend (only required with PHP >= 7.0), cron will send a bunch of emails with errors like:

PHP Warning: error_reporting() has been disabled for security reasons in /var/www/html/wp-load.php on line 24
PHP Warning: error_reporting() has been disabled for security reasons in /var/www/html/wp-includes/load.php on line 333

Some Linux ninja allows us to filter out specific error messages instead of silencing them all (we still want cron to alert us of potential WordPress errors):

* * * * * /usr/bin/php /var/www/html/wp-cron.php 2>&1 | grep -v 'PHP Warning:  error_reporting() has been disabled for security reasons'

WP-CLI based cron

WordPress CLI command line utility can be used to run crons. I have seen this approach mentioned. Not yet sure on the benefits or downsides compared to wp-cron.php:

*/5 * * * * WP_CLI_CONFIG_PATH="$WP_PATH/wp-cli.yml" /usr/local/bin/wp --path="$WP_PATH" cron event run --due-now > /dev/null
Exit mobile version