Log Scheduled Tasks That Take Too Long
Measures how long each scheduled task (cron event) takes to run and records the slow ones under Tools > Slow Cron Tasks, so you can spot the plugin that makes WP-Cron sluggish.
Opens WPIDE on
Code
// Tasks slower than this many seconds are logged.
$wpide_cron_slow = 3;
add_action( 'init', function () use ( $wpide_cron_slow ) {
if ( ! wp_doing_cron() ) {
return;
}
foreach ( (array) _get_cron_array() as $time => $hooks ) {
if ( $time > time() ) {
break;
}
foreach ( array_keys( (array) $hooks ) as $hook ) {
add_action( $hook, function () use ( $hook ) {
$GLOBALS['wpide_cron_start'][ $hook ] = microtime( true );
}, PHP_INT_MIN );
add_action( $hook, function () use ( $hook, $wpide_cron_slow ) {
if ( empty( $GLOBALS['wpide_cron_start'][ $hook ] ) ) {
return;
}
$took = microtime( true ) - $GLOBALS['wpide_cron_start'][ $hook ];
if ( $took >= $wpide_cron_slow ) {
$log = (array) get_option( 'wpide_slow_cron', array() );
$log[ $hook ] = array( 'time' => round( $took, 2 ), 'when' => time(), 'max' => max( $took, isset( $log[ $hook ]['max'] ) ? (float) $log[ $hook ]['max'] : 0 ) );
update_option( 'wpide_slow_cron', array_slice( $log, -50, null, true ), false );
}
}, PHP_INT_MAX );
}
}
}, 99 );
add_action( 'admin_menu', function () {
add_management_page( 'Slow Cron Tasks', 'Slow Cron Tasks', 'manage_options', 'wpide-slow-cron', function () {
$log = (array) get_option( 'wpide_slow_cron', array() );
echo '<div class="wrap"><h1>Slow Cron Tasks</h1><table class="widefat striped"><thead><tr><th>Hook</th><th>Last run</th><th>Slowest run</th><th>When</th></tr></thead><tbody>';
if ( ! $log ) {
echo '<tr><td colspan="4">No slow tasks recorded yet.</td></tr>';
}
foreach ( $log as $hook => $row ) {
printf( '<tr><td><code>%s</code></td><td>%ss</td><td>%ss</td><td>%s</td></tr>', esc_html( $hook ), esc_html( $row['time'] ), esc_html( round( (float) $row['max'], 2 ) ), esc_html( human_time_diff( (int) $row['when'] ) . ' ago' ) );
}
echo '</tbody></table></div>';
} );
} );
Notes
Only runs during cron requests; tasks faster than $wpide_cron_slow seconds are not recorded.
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.