From 31e1b55c6a35fb4c1e06e164f93399fa683cd925 Mon Sep 17 00:00:00 2001 From: Jb Audras Date: Tue, 20 Sep 2022 15:15:55 +0000 Subject: [PATCH] Cron API: Add error logging and hooks to `wp-cron.php`. This changeset adds error logging on `wp_reschedule_event()` and `wp_unschedule_event` in `wp-cron.php`. This allows proper error logging when random errors appear. It also introduces `cron_reschedule_event_error` and `cron_unschedule_event_error` hooks which can be used to trigger additional behaviors when an error occurs. Props Enchiridion, johnbillion, costdev. Fixes #56048. git-svn-id: https://develop.svn.wordpress.org/trunk@54258 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-cron.php | 52 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/src/wp-cron.php b/src/wp-cron.php index ceaf5d1e65..164e4ef191 100644 --- a/src/wp-cron.php +++ b/src/wp-cron.php @@ -123,10 +123,58 @@ foreach ( $crons as $timestamp => $cronhooks ) { $schedule = $v['schedule']; if ( $schedule ) { - wp_reschedule_event( $timestamp, $schedule, $hook, $v['args'] ); + $result = wp_reschedule_event( $timestamp, $schedule, $hook, $v['args'], true ); + + if ( is_wp_error( $result ) ) { + error_log( + sprintf( + /* translators: 1: Hook name, 2: Error code, 3: Error message, 4: Event data. */ + __( 'Cron reschedule event error for hook: %1$s, Error code: %2$s, Error message: %3$s, Data: %4$s' ), + $hook, + $result->get_error_code(), + $result->get_error_message(), + wp_json_encode( $v ) + ) + ); + + /** + * Fires when an error happens rescheduling a cron event. + * + * @since 6.1.0 + * + * @param WP_Error $result The WP_Error object. + * @param string $hook Action hook to execute when the event is run. + * @param array $v Event data. + */ + do_action( 'cron_reschedule_event_error', $result, $hook, $v ); + } } - wp_unschedule_event( $timestamp, $hook, $v['args'] ); + $result = wp_unschedule_event( $timestamp, $hook, $v['args'], true ); + + if ( is_wp_error( $result ) ) { + error_log( + sprintf( + /* translators: 1: Hook name, 2: Error code, 3: Error message, 4: Event data. */ + __( 'Cron unschedule event error for hook: %1$s, Error code: %2$s, Error message: %3$s, Data: %4$s' ), + $hook, + $result->get_error_code(), + $result->get_error_message(), + wp_json_encode( $v ) + ) + ); + + /** + * Fires when an error happens unscheduling a cron event. + * + * @since 6.1.0 + * + * @param WP_Error $result The WP_Error object. + * @param string $hook Action hook to execute when the event is run. + * @param array $v Event data. + */ + do_action( 'cron_unschedule_event_error', $result, $hook, $v ); + } /** * Fires scheduled events.