plugin = $plugin; } public function register(): void { add_filter( 'cron_schedules', array( self::class, 'addIntervals' ) ); add_action( self::HOOK, array( $this, 'run' ) ); add_action( self::CONTINUE, array( $this, 'resume' ) ); // A site restored from a backup, or a cron table that was emptied, must not silently lose its schedule. add_action( 'init', array( self::class, 'heal' ) ); } /** * @param array $schedules * @return array */ public static function addIntervals( array $schedules ): array { $schedules[ self::MONTHLY ] = array( 'interval' => 30 * DAY_IN_SECONDS, 'display' => __( 'Once a month (MigrateX)', 'migratex' ), ); return $schedules; } /** * @param string $frequency daily, weekly or monthly. */ public static function recurrence( string $frequency ): string { switch ( $frequency ) { case ScheduleCalc::WEEKLY: return 'weekly'; case ScheduleCalc::MONTHLY: return self::MONTHLY; default: return 'daily'; } } /** * When the next backup is due for these settings. * * @param array $settings */ public static function nextRun( array $settings, ?int $from = null ): int { return ScheduleCalc::nextRun( (string) $settings['frequency'], (int) $settings['hour'], (int) $settings['minute'], (int) $settings['weekday'], (int) $settings['monthday'], $from ?? time(), wp_timezone() ); } /** * Replaces whatever is scheduled with what the settings ask for. * * @param array $settings * @return int|null The next run, or null when the schedule is off. */ public static function apply( array $settings ): ?int { wp_clear_scheduled_hook( self::HOOK ); if ( empty( $settings['enabled'] ) ) { wp_clear_scheduled_hook( self::CONTINUE ); return null; } $next = self::nextRun( $settings ); wp_schedule_event( $next, self::recurrence( (string) $settings['frequency'] ), self::HOOK ); return $next; } /** * When the event is next due, as WP-Cron has it. */ public static function scheduledFor(): ?int { $next = wp_next_scheduled( self::HOOK ); return false === $next ? null : (int) $next; } public static function heal(): void { $settings = ScheduleSettings::get(); $next = self::scheduledFor(); if ( ! empty( $settings['enabled'] ) && null === $next ) { self::apply( $settings ); } elseif ( empty( $settings['enabled'] ) && null !== $next ) { self::apply( $settings ); } } public static function unschedule(): void { wp_clear_scheduled_hook( self::HOOK ); wp_clear_scheduled_hook( self::CONTINUE ); } /** * The recurring event, or a postponed retry of it. * * @param int $retry How many times this run has already been put off (0 for the scheduled one). */ public function run( $retry = 0 ): void { ( new ScheduledBackup( $this->plugin ) )->run( (int) $retry ); } /** * Carries on a backup that did not finish inside one cron request. * * @param string $job_id */ public function resume( $job_id = '' ): void { ( new ScheduledBackup( $this->plugin ) )->resume( (string) $job_id ); } }