$e->getMessage() ) ); } } /** * Whether anything still needs the tick. A failed read counts as work. * * Any job in a status the tick works in counts, a future-dated `ready` job * too: the tick is the safety net for a lost run event of such a job. * * @return bool */ public static function hasWork(): bool { global $wpdb; $table = $wpdb->prefix . 'aipt_automation_jobs'; $placeholders = implode( ', ', array_fill( 0, count( AutomationJob::TICK_STATUSES ), '%s' ) ); // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Table name from $wpdb->prefix; the status list is a class constant bound through placeholders. $job = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$table} WHERE status IN ({$placeholders}) LIMIT 1", AutomationJob::TICK_STATUSES ) ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching if ( null !== $job || '' !== (string) $wpdb->last_error ) { return true; } $reasons = apply_filters( self::REASONS_FILTER, array() ); return ! is_array( $reasons ) || array() !== $reasons; } /** * Last callback of the tick: remove the event when there is no work. * * WordPress has already rescheduled the next run before any callback ran, * so the whole hook is cleared. Work that appeared between the first look * and the clear (a hold armed on another request) re-arms it. A tick that * dies before this callback leaves the event in place, which is safe, and a * failure inside it arms the event again: after the clear, a look that * throws could otherwise leave work with no tick and a flag that stops the * `wp_loaded` repair. * * @return void */ public static function settle(): void { try { if ( self::hasWork() ) { return; } update_option( self::OPTION, '0', true ); wp_clear_scheduled_hook( self::HOOK ); if ( self::hasWork() ) { self::ensureScheduled(); } } catch ( \Throwable $e ) { Logger::error( 'cron', 'Automation tick could not settle', array( 'error' => $e->getMessage() ) ); self::ensureScheduled(); } } }