Kinsta CRON Jobs For WordPress Using WP-CLI

clear hour glass with red background

I use Kinsta hosting for the WordPress sites I run at Business Website Leader. Part of my deployment process is to set up proper Kinsta cron jobs at the server level using the wp-cli.

Kinsta has a proper cron already set up for each site you create. However, they do not disable the WordPress poor-man-cron or set the cron intervals to a frequency I like (every five minutes).

First, I like to disable the WordPress poor-man-cron by adding the following to a site’s wp-config.php.

define('DISABLE_WP_CRON', true);

On Kinsta, this will not stop cron from running because each server has server-level cron enabled by default. DISABLE_WP_CRON only disables the WordPress poor-man-cron.

Next, I SSH into the server and edit the crontab with crontab -e. Now, I can set the interval to 5 minutes with */5 * * * *.

*/5 * * * * curl -kILs -H 'Host: example.com' https://localhost/wp-cron.php?server_triggered_cronjob >/dev/null 2>&1 # Kinsta Primary domain cron

This works well. But, I like to use the wp-cli for cron jobs. Here is how that looks:

*/5 * * * * /usr/local/bin/wp cron event run --due-now --path=/www/examplesite_098/public --url=https://example.com

And, that’s it. Cron is now working using the wp-cli on Kinsta WordPress hosting.

UptimeRobot

To ensure cron is working as expected I also set up a heartbeat check using UptimeRobot. I will not go into detail on how UptimeRobot heartbeat checks work outside of showing you a screenshot.

uptime robot cron example
UptimeRobot Heartbeat Cron

Here, I have created a heartbeat monitor with an interval equal to my wp-cli (five minutes). The heartbeat monitor provides a unique URL that should be pinged by your cron at that interval or faster.

Next, I add the following to my WordPress theme or a custom plugin. This code will get trigger by the server cron.

// Cron
add_action( 'bz_cron_hook', 'bz_cron_hook_action' );
function bz_cron_hook_action()
{
    if(defined('BWL_CRON_MONITOR_URL')) {
        wp_remote_get(BZ_CRON_MONITOR_URL)->exec();
    }
}

add_filter( 'cron_schedules', 'bz_cron_interval' );
function bz_cron_interval( $schedules ) {
    $schedules['five_minutes'] = array(
        'interval' => 60 * 5,
        'display'  => esc_html__( 'Every 5 Minutes' ), );
    return $schedules;
}

if ( ! wp_next_scheduled( 'bz_cron_hook' ) ) {
    wp_schedule_event( time(), 'five_minutes', 'bz_cron_hook' );
}

Finally, I define BZ_CRON_MONITOR_URL in the wp-config.php file.

define('BZ_CRON_MONITOR_URL', 'https://heartbeat.uptimerobot.com/….’);

You can then list the events using wp-cli:

wp cron schedule list

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.