1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
<?php
namespace SIW;
class Scheduler {
const TS_SCHEDULED_JOBS = '03:00';
const TS_UPDATE_PROJECTS = '1:00';
const TS_UPDATE_FREE_PLACES = '2:00';
const OPTION_NAME = 'siw_scheduled_cron_jobs';
const CRON_JOB_INTERVAL = 5;
protected static $jobs = [];
public static function init() {
$self = new self();
add_action( 'siw_update_plugin', [ $self, 'schedule_events'] );
}
public function schedule_events() {
$this->unschedule_jobs();
$this->schedule_jobs();
$this->schedule_update_free_places();
$this->schedule_update_projects();
}
protected function schedule_jobs() {
$timestamp = Util::convert_timestamp_to_gmt( strtotime( 'tomorrow ' . self::TS_SCHEDULED_JOBS ) );
foreach ( self::$jobs as $index => $job ) {
wp_schedule_event( $timestamp + ( $index * self::CRON_JOB_INTERVAL * MINUTE_IN_SECONDS ), 'daily', $job );
}
$this->set_scheduled_jobs( self::$jobs );
}
protected function schedule_update_free_places() {
$new_timestamp = Util::convert_timestamp_to_gmt( strtotime( 'tomorrow ' . self::TS_UPDATE_FREE_PLACES ) );
if ( wp_next_scheduled( 'siw_update_free_places' ) ) {
wp_clear_scheduled_hook( 'siw_update_free_places' );
}
wp_schedule_event( $new_timestamp, 'daily', 'siw_update_free_places' );
}
protected function schedule_update_projects() {
$new_timestamp = Util::convert_timestamp_to_gmt( strtotime( 'tomorrow ' . self::TS_UPDATE_PROJECTS ) );
if ( wp_next_scheduled( 'siw_update_workcamps' ) ) {
wp_clear_scheduled_hook( 'siw_update_workcamps' );
}
wp_schedule_event( $new_timestamp, 'daily', 'siw_update_workcamps' );
}
public static function add_job( string $hook ) {
self::$jobs[] = $hook;
}
protected function unschedule_jobs() {
$scheduled_jobs = $this->get_scheduled_jobs();
foreach ( $scheduled_jobs as $job ) {
if ( wp_next_scheduled( $job ) ) {
wp_clear_scheduled_hook( $job );
}
}
}
protected function get_scheduled_jobs() {
return (array) get_option( self::OPTION_NAME );
}
protected function set_scheduled_jobs( array $jobs = [] ) {
update_option( self::OPTION_NAME, $jobs, false );
}
}