order_sync = $order_sync; add_filter( 'cron_schedules', array( $this, 'add_schedule' ) ); // phpcs:ignore WordPress.WP.CronInterval.CronSchedulesInterval add_action( self::HOOK, array( $this, 'run_retry' ) ); // Self-heal on every load, in whichever direction the Order Delay // setting currently calls for: // - On, but the recurring event is missing for some other reason // (e.g. activation didn't run under this code, deactivate/ // reactivate, a cron-clearing plugin) — schedule it, otherwise the // queue would sit stuck in "Pending" forever with nothing to flush it. // - Off, but the event is still scheduled (e.g. it was turned off // after being on, or the option changed outside Settings) — clear // it, otherwise the cron keeps firing after the setting says it // shouldn't. self::maybe_schedule_or_clear(); } /** * Register the retry interval, computed from the configured setting. * * @param array $schedules Schedules. * @return array */ public function add_schedule( $schedules ) { $minutes = self::get_interval_minutes(); $schedules[ self::SCHEDULE_KEY ] = array( 'interval' => $minutes * MINUTE_IN_SECONDS, /* translators: %d: interval in minutes */ 'display' => sprintf( __( 'Every %d minutes (WSE ACS Sync for WooCommerce)', 'weship-acs-sync-for-woocommerce' ), $minutes ), ); return $schedules; } /** * Retry queued/failed orders on every run — there is no separate * enable/disable flag; the Order Delay interval alone drives this. */ public function run_retry() { $this->order_sync->retry_pending_orders(); } /** * Get the configured retry interval in minutes, falling back to 5. * * @return int */ public static function get_interval_minutes() { $minutes = (int) Weship_ACS_Sync_Api_Client::get_setting( 'order_delay_interval', 5 ); return in_array( $minutes, self::ALLOWED_INTERVALS, true ) ? $minutes : 5; } /** * (Re)schedule the retry cron event to run every $minutes, starting now. * Called on activation and whenever the interval setting changes. * * @param int|null $minutes Interval in minutes; defaults to the configured setting. */ public static function schedule( $minutes = null ) { $minutes = null === $minutes ? self::get_interval_minutes() : $minutes; $minutes = in_array( (int) $minutes, self::ALLOWED_INTERVALS, true ) ? (int) $minutes : 5; wp_clear_scheduled_hook( self::HOOK ); wp_schedule_event( time() + ( $minutes * MINUTE_IN_SECONDS ), self::SCHEDULE_KEY, self::HOOK ); } /** * Make the cron event match the Order Delay setting: scheduled when * it's on, cleared when it's off. Idempotent either way, so it's safe * to call on every load as well as right after a settings save. */ public static function maybe_schedule_or_clear() { if ( 'yes' === Weship_ACS_Sync_Api_Client::get_setting( 'order_delay', 'no' ) ) { if ( ! wp_next_scheduled( self::HOOK ) ) { self::schedule(); } } else { wp_clear_scheduled_hook( self::HOOK ); } } }