What are Cronjobs ?
Cron is one of the most useful utilities for websites. It is used to schedule tasks to run at a specific time. These scheduled tasks are called “Cronjobs”. They are generally used to perform extensive tasks in the background without affecting the usability of the website. These tasks can be checking the update of plugins, optimizing the cache, importing data or optimizing images.
WordPress case
By default, WordPress does not use a real cronjob to perform these extensive tasks. Instead, WordPress executes the wp-cron.php file every time a page is loaded on a WordPress website. This technique is known as the “poor man’s cron” and has drawbacks:
WP-Cron is executed every time WordPress loads a page. This can have a negative impact on server performance, especially if the website has many visitors.
For a small website with few visitors, it can increase the page load as heavy tasks are started when a visitor loads a page (and triggers the cron task). This can cause post publishing schedules to be missed and have other unintended effects.
Setup Cronjobs
Step 1 : Disable the Poor man’s cron
Edit the wp-config.php and add the following line at the end:
define('DISABLE_WP_CRON', true);
Step 2 : Setup Cron
Method 1 : Command line approach
If you have command line access to your server, set up a new cron task with the following command:
crontab -e
This will open a text editor. Simply insert the following line by replacing the path with the path of your website:
*/15 * * * * cd /your/path/to/website; php -q wp-cron.php
This command executes cron operations every 15 minutes (recommended)
Method 2 : Use the control panel provided by your hosting provider
Your hosting provider should provide you with a web interface for setting up cron jobs (such as cPanel or OVH Manager). You can declare your cron job on this interface. Schedule it every 15 minutes and run the following command (customize the path)
cd /your/path/to/website; php -q wp-cron.php
Bypass duration of execution limit
In some cases, your hosting provider will apply the default php.ini, which limits the script duration to a maximum of 30 seconds. You can specify a custom php.ini with a higher value for max_execution_time (e.g. 300 seconds) by using the following syntax:
cd /your/path/to/website; php -c /path/to/php.ini -q wp-cron.php