Skip to content

Instantly share code, notes, and snippets.

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 michaeluno/77de98e171d837e428aad2842be4a37b to your computer and use it in GitHub Desktop.
Save michaeluno/77de98e171d837e428aad2842be4a37b to your computer and use it in GitHub Desktop.
Cleans up hung routines of Task Scheduler WordPress plugin.
<?php
/**
* Plugin Name: Task Scheduler - Hung Routine Cleaner
* Description: Cleans up hung routines.
* Author: Michael Uno
* Version: 1.0.0
*/
class TaskSchedulerHungRoutineCleaner {
public $iElapsedTime = 1800; // seconds - 30 minutes
public $iCheckInterval = 43200; // seconds - 12 hours
private $___sPeriodicalCheckActionName = "task_scheduler_hung_routine_cleaner_action_periodical_check";
public function __construct() {
add_action( 'task_scheduler_action_after_loading_plugin', array( $this, 'load' ) );
}
/**
* @remark This method will only be called when the Task Scheduler plugin is activated.
*/
public function load() {
add_action( $this->___sPeriodicalCheckActionName, array( $this, 'deleteHungRoutines' ) );
$this->_scheduleToCheckBeat();
}
public function deleteHungRoutines() {
$_aRoutineIDs = $this->_getProcessing( $this->iElapsedTime );
$this->_deleteRoutines( $_aRoutineIDs );
}
private function _deleteRoutines( array $aRoutineIDs ) {
foreach( $aRoutineIDs as $_iRoutineID ) {
$_oRoutine = TaskScheduler_Routine::getInstance( $_iRoutineID );
$_oRoutine->delete();
}
}
private function _scheduleToCheckBeat() {
if ( wp_next_scheduled( $this->___sPeriodicalCheckActionName ) ) {
return;
}
wp_schedule_single_event( time() + $this->iCheckInterval, $this->___sPeriodicalCheckActionName );
}
/**
* Returns the array of holding routine(task/thread) IDs that are processing and awaiting.
*
* @return array An array holding the found routine(post) IDs.
*/
private function _getProcessing( $iElapsedSeconds, $iLimit=-1 ) {
$_aArgs = array(
'posts_per_page' => $iLimit, // -1 for all
'meta_query' => array(
'relation' => 'AND', // or 'OR' can be specified
array( // do not select tasks of empty values of the _next_run_time key.
'key' => '_routine_status',
'value' => array( 'processing' ),
'compare' => 'IN',
),
array(
'key' => '_spawned_time',
'value' => microtime( true ) - $iElapsedSeconds,
'type' => 'numeric',
'compare' => '<=',
),
),
);
$_oResults = TaskScheduler_RoutineUtility::find( $_aArgs );
return $_oResults->posts;
}
}
new TaskSchedulerHungRoutineCleaner;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment