recorder = $recorder; $this->repository = $repository; } public function register(): void { add_action( 'init', array( $this, 'schedule' ) ); add_action( self::HOOK_DAILY, array( $this, 'start_daily' ) ); add_action( self::HOOK_BATCH, array( $this, 'run_batch' ), 10, 2 ); } /** * Scheduling checks query the database, so they run only where jobs are * managed (admin, cron, WP-CLI), not on every storefront page view. */ public static function is_maintenance_request(): bool { return is_admin() || wp_doing_cron() || ( defined( 'WP_CLI' ) && WP_CLI ); } public function schedule(): void { if ( ! function_exists( 'as_has_scheduled_action' ) || ! self::is_maintenance_request() ) { return; } if ( ! as_has_scheduled_action( self::HOOK_DAILY, array(), self::GROUP ) ) { $first = ( new \DateTimeImmutable( 'tomorrow 03:00', wp_timezone() ) )->getTimestamp(); as_schedule_recurring_action( $first, DAY_IN_SECONDS, self::HOOK_DAILY, array(), self::GROUP ); } if ( get_option( self::OPTION_SEED_PENDING ) ) { delete_option( self::OPTION_SEED_PENDING ); as_enqueue_async_action( self::HOOK_BATCH, array( 1, 'seed' ), self::GROUP ); } } public function start_daily(): void { $this->repository->cleanup( Settings::retention_days(), Settings::window_days() ); as_enqueue_async_action( self::HOOK_BATCH, array( 1, 'sync' ), self::GROUP ); } /** * @param int|string $page * @param string $source */ public function run_batch( $page, $source = 'sync' ): void { $page = max( 1, (int) $page ); $source = in_array( $source, array( 'sync', 'seed' ), true ) ? $source : 'sync'; $ids = get_posts( array( 'post_type' => array( 'product', 'product_variation' ), 'post_status' => array( 'publish', 'private', 'draft', 'pending', 'future' ), 'fields' => 'ids', 'posts_per_page' => self::BATCH_SIZE, 'paged' => $page, 'orderby' => 'ID', 'order' => 'ASC', 'no_found_rows' => true, ) ); foreach ( $ids as $id ) { $product = wc_get_product( $id ); if ( $product ) { $this->recorder->record( $product, $source ); } } if ( count( $ids ) === self::BATCH_SIZE ) { as_enqueue_async_action( self::HOOK_BATCH, array( $page + 1, $source ), self::GROUP ); } } public static function unschedule_all(): void { if ( function_exists( 'as_unschedule_all_actions' ) ) { as_unschedule_all_actions( self::HOOK_DAILY, array(), self::GROUP ); as_unschedule_all_actions( self::HOOK_BATCH, null, self::GROUP ); as_unschedule_all_actions( 'strikewise_weekly_scan', array(), self::GROUP ); as_unschedule_all_actions( 'strikewise_cockpit_weekly', array(), self::GROUP ); } } }