Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Forked from ryanshoover/retry-failed.php
Created July 6, 2023 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jchristopher/34738ff736e80172067fa84768cf40d8 to your computer and use it in GitHub Desktop.
Save jchristopher/34738ff736e80172067fa84768cf40d8 to your computer and use it in GitHub Desktop.
Action Scheduler retry failed jobs
<?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