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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.