WP-Cron is how WordPress handles scheduling time-based tasks in WordPress. Several WordPress core features, such as checking for updates and publishing scheduled posts, utilize WP-Cron.
WP-Cron executes on every page load. If there is a long-running process that gets triggered by WP-Cron, it will delay page loading for the user.
Cron has a specific syntax that needs to be followed and contains the following parts:
- Minute
- Hour
- Day of month
- Month
- Day of week
- Command to execute
Why use WP-Cron?
- WordPress core and many plugins need a scheduling system to perform time-based tasks. However, many hosting services are shared and do not provide access to the system scheduler.
- Using the WordPress API is a simpler method for setting scheduled tasks than going outside of WordPress to the system scheduler.
- With the system scheduler, if the time passes and the task did not run, it will not be re-attempted. With WP-Cron, all scheduled tasks are put into a queue and will run at the next opportunity (meaning the next page load). So while you can’t be 100% sure when your task will run, you can be 100% sure that it will run eventually.
Using crontab, WP-cron is run by an independent PHP process. Thus not interfering with any visitors’ page requests. Because of this, we highly recommend running wp-cron via Linux crontab rather than WordPress’s default way, irrespective of the size or traffic of your site.
Disable WP-Cron
We will first need to disable WordPress default wp-cron behaviour by adding the following line to the wp-config.php file:
define('DISABLE_WP_CRON', true);
Setting up a real cron job
From your Linux terminal, first, open crontab:
crontab -e
Then add a line like below in it.
*/5 * * * * curl http://example.com/wp-cron.php?doing_wp_cron > /dev/null 2>&1
The above command uses PHP-FPM (or PHP-CGI).
OR
*/5 * * * * cd /var/www/example.com/htdocs; php /var/www/example.com/htdocs/wp-cron.php?doing_wp_cron > /dev/null 2>&1
The above command uses PHP-CLI. CLI scripts do not have time limits. Depending on your setup, it may be desirable or undesirable.
Please make sure you use the correct path to wp-cron.php.
Alternately, you can also use WP-CLI
*/5 * * * * cd /var/www/example.com/htdocs; wp cron event run --due-now > /dev/null 2>&1
Above will run wp-cron every 5 minutes. You can change */5 to */10 to make it run every 10 minutes.
Note: You can request your host to set up the CRON jobs for your website or create a cron job directly from your host’s account page. Here is a step-by-step guide on how to set up a cron job for your websites on the Cloudways Platform.