Halloween Sale 15% off Ends in See the plans
PHP

Email Alert When WP-Cron Stops Running

Warns the admin by email when scheduled tasks are more than an hour overdue, so you notice before scheduled posts, digests and backups silently stop.

Don’t have WPIDE yet? Install it on your site

Code

$wpide_cron_late_minutes = 60;

add_action( 'admin_init', function () use ( $wpide_cron_late_minutes ) {
    if ( wp_doing_ajax() || ! current_user_can( 'manage_options' ) || get_transient( 'wpide_cron_checked' ) ) {
        return;
    }
    set_transient( 'wpide_cron_checked', 1, HOUR_IN_SECONDS );

    $crons = _get_cron_array();
    if ( ! is_array( $crons ) || ! $crons ) {
        return;
    }

    $oldest = (int) min( array_keys( $crons ) );
    $late   = time() - $oldest;

    if ( $late < $wpide_cron_late_minutes * MINUTE_IN_SECONDS || get_transient( 'wpide_cron_alert_sent' ) ) {
        return;
    }

    set_transient( 'wpide_cron_alert_sent', 1, DAY_IN_SECONDS );
    $hooks = array_keys( (array) $crons[ $oldest ] );

    wp_mail(
        get_option( 'admin_email' ),
        sprintf( '[%s] Scheduled tasks are not running', wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ) ),
        sprintf( "The oldest scheduled task (%s) is %s overdue, which means WP-Cron is not running.\n\nCheck that DISABLE_WP_CRON is not set without a real server cron job, and that your site can make requests to itself.", implode( ', ', $hooks ), human_time_diff( $oldest ) )
    );
} );

Notes

The check runs when an administrator loads the admin, so it works even when cron itself is broken; at most one alert per day.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.