Skip to content

Instantly share code, notes, and snippets.

@bhubbard
Created December 10, 2024 22:07
Show Gist options
  • Save bhubbard/4592175d960ae18a02d2bb10edc693a2 to your computer and use it in GitHub Desktop.
Save bhubbard/4592175d960ae18a02d2bb10edc693a2 to your computer and use it in GitHub Desktop.
This pattern automatically retries a failed WP Cron job with a configurable number of retry attempts and a delay between retries.
How It Works:
• When the cron job fails, it increments a retry count and schedules a retry attempt after a set delay.
• It will attempt to retry the job a maximum of MY_CRON_JOB_MAX_RETRIES times, with a delay of MY_CRON_JOB_RETRY_DELAY between each retry.
• After successful execution or after reaching the retry limit, the retry count is reset.
<?php
/**
* Cron Job Failure Retry Pattern
*
* Automatically retries a failed WP Cron job with configurable retries and delay.
*/
// Define retry parameters
define( 'MY_CRON_JOB_MAX_RETRIES', 3 );
define( 'MY_CRON_JOB_RETRY_DELAY', 300 ); // 5 minutes
// Cron job callback
function my_cron_job_callback() {
// Simulate a task (e.g., a task that can fail)
$task_successful = false; // Simulate a failure
if ( ! $task_successful ) {
// Log the failure and trigger retry
error_log( 'Cron job failed. Scheduling retry.' );
my_cron_job_schedule_retry();
} else {
error_log( 'Cron job executed successfully.' );
}
}
// Schedule a retry if the job fails
function my_cron_job_schedule_retry() {
$retry_count = get_option( 'my_cron_job_retry_count', 0 );
if ( $retry_count < MY_CRON_JOB_MAX_RETRIES ) {
// Increment the retry count
update_option( 'my_cron_job_retry_count', ++$retry_count );
// Schedule the retry
wp_schedule_single_event( time() + MY_CRON_JOB_RETRY_DELAY, 'my_cron_job_retry_hook' );
} else {
error_log( 'Max retries reached. Cron job will not be retried further.' );
}
}
// Reset retry count once the job succeeds or after max retries
function my_cron_job_reset_retry_count() {
delete_option( 'my_cron_job_retry_count' );
}
// Schedule the cron job if not already scheduled
if ( ! wp_next_scheduled( 'my_cron_job_hook' ) ) {
wp_schedule_event( time(), 'hourly', 'my_cron_job_hook' );
}
// Hook the cron job retry logic
add_action( 'my_cron_job_hook', 'my_cron_job_callback' );
// Hook to reset retry count after job success
add_action( 'my_cron_job_retry_hook', 'my_cron_job_reset_retry_count' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment