Files
WP-Site-Sync/includes/class-cron.php
2025-12-14 16:58:52 -06:00

107 lines
2.9 KiB
PHP

<?php
namespace SiteSync;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles scheduling and execution of Site Sync cron jobs.
*/
class Cron {
public const HOOK = 'site_sync_run';
public const DEFAULT_INTERVAL = 'site_sync_5min';
/**
* Site Sync settings instance.
*
* @var Settings
*/
private $settings;
/**
* Cron constructor.
*
* @param Settings $settings Site Sync settings instance.
*/
public function __construct( Settings $settings ) {
$this->settings = $settings;
}
/**
* Registers cron schedule and sync run hooks.
*
* @return void
*/
public function hooks(): void {
add_filter( 'cron_schedules', array( $this, 'add_schedule' ) ); // phpcs:ignore
add_action( self::HOOK, array( $this, 'run_sync' ) );
}
/**
* Adds a custom schedule interval for Site Sync cron jobs.
*
* @param array $schedules Existing cron schedules.
* @return array Modified cron schedules with Site Sync interval.
*/
public function add_schedule( array $schedules ): array {
if ( ! isset( $schedules[ self::DEFAULT_INTERVAL ] ) ) {
$schedules[ self::DEFAULT_INTERVAL ] = array(
'interval' => 5 * MINUTE_IN_SECONDS,
'display' => __( 'Every 5 minutes (Site Sync)', 'site-sync' ),
);
}
return $schedules;
}
/**
* Configures the Site Sync cron event by enabling or disabling it and setting the interval.
*
* @param bool $enabled Whether to enable the cron event.
* @param string $interval The interval for the cron event. Defaults to self::DEFAULT_INTERVAL.
*
* @return void
*/
public static function configure( bool $enabled, string $interval = self::DEFAULT_INTERVAL ): void {
$interval = $interval ? $interval : self::DEFAULT_INTERVAL;
if ( $enabled ) {
// Reset any existing schedule to honor new intervals.
wp_clear_scheduled_hook( self::HOOK );
wp_schedule_event( time() + MINUTE_IN_SECONDS, $interval, self::HOOK );
} else {
self::clear_event();
}
}
/**
* Clears the scheduled Site Sync cron event.
*
* @return void
*/
public static function clear_event(): void {
wp_clear_scheduled_hook( self::HOOK );
}
/**
* Executes the Site Sync cron job by triggering the sync cycle action.
*
* @return void
*/
public function run_sync(): void {
$settings = $this->settings->get_settings();
if ( empty( $settings['enabled'] ) ) {
return;
}
/**
* Hook to start a sync cycle. The actual sync implementation will be
* attached by the sync engine to process outbound and inbound batches.
*/
do_action( 'site_sync/run_cycle', $settings );
}
}