Created
May 18, 2022 20:06
-
-
Save ryanshoover/83cc871056fc0e8f38bcb2fceb76ed27 to your computer and use it in GitHub Desktop.
Action Scheduler retry failed jobs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Instance of the batch processing job. | |
$job = MyBatchJob(); | |
// How many failed attempts do you want to process. | |
$batch_max_attempts = 3; | |
add_action( 'action_scheduler_failed_execution', 'maybe_retry_failed_batch' ); | |
add_action( 'action_scheduler_failed_action', 'maybe_retry_failed_batch' ); | |
add_action( 'action_scheduler_unexpected_shutdown', 'maybe_retry_failed_batch' ); | |
function maybe_retry_failed_batch( $action_id ) { | |
$action = \ActionScheduler::store()->fetch_action( $action_id ); | |
// If this isn't from our group, bail. | |
if ( $action->get_group() !== $job->get_group_name() ) { | |
return; | |
} | |
// Strip out all the extra content from the hook name. | |
$hook = str_replace( [ $job->get_plugin_name(), 'jobs', 'chain_batch', '/' ], '', $action->get_hook() ); | |
// Only run if the hook is for our job. | |
if ( $hook !== $job->get_name() ) { | |
return; | |
} | |
// Get the number of attempts from the database. AS currently doesn't reveal it through their APIs. | |
global $wpdb; | |
$attempts = $wpdb->get_var( | |
$wpdb->prepare( | |
"SELECT attempts FROM $wpdb->actionscheduler_actions WHERE action_id=%d", | |
$action_id | |
) | |
); | |
// If we've already tried as much as we should, bail. | |
if ( $batch_max_attempts <= intval( $attempts ) ) { | |
return; | |
} | |
// The batch number is the first index in args. | |
$args = $action->get_args(); | |
$job->handle_batch_action( $args[0], $args[1] ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment