arraypress / wp-register-cron
Declarative WordPress cron jobs and custom schedules, and Action Scheduler jobs that are deferred, deduplicated, retried, recurring or due at a local time -- all cleaned up properly on uninstall.
Requires
- php: >=8.3
Requires (Dev)
- phpcompatibility/phpcompatibility-wp: ^2.1
- phpunit/phpunit: ^12.0
- squizlabs/php_codesniffer: ^3.13.5
- wp-coding-standards/wpcs: ^3.4
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
This library has moved. It is now part of
sugarcommerce/jobs(namespaceSugarCommerce\Jobs, PHP 8.3+). That package's README has a "Moving from arraypress/wp-*" table. This repository is archived and read-only.
Register Cron
Declare a plugin's scheduled jobs, on WP-Cron or Action Scheduler, and have them cleaned up properly when it is removed.
What it does
Scheduling in WordPress is two calls that must not disagree:
wp_next_scheduled() before wp_schedule_event(), on the right hook, with
the right arguments — and then the same arguments again at uninstall or the
job is left behind forever, firing for a plugin that is no longer there.
This is the declaration instead. You say what should run and how often; the scheduling, the duplicate check and the uninstall are handled. For work that must not happen during a save — telling a payment provider a product changed, posting a webhook — the same declarations run on Action Scheduler, with deduplication, retries and a time of day that survives the clocks changing.
Features
- Declare a job once, instead of guarding
wp_schedule_event()by hand - Add a schedule WordPress does not have, like every five minutes
- Push slow work out of a save, queued once however many times it is saved
- Retry what failed on a stated schedule, and hear about it once when it gives up
- Run a job at eight in the morning where the site is, every Monday or every 1st
- Keep a schedule level with a setting: off, weekly or monthly
- Unschedule everything the plugin registered, in one call at uninstall
- Keep working, by running jobs in place, where Action Scheduler is missing
Installation
composer require arraypress/wp-register-cron
Quick start
add_action( 'init', function () { register_cron_job( 'myplugin_sync', [ 'schedule' => 'daily', 'callback' => 'myplugin_run_sync', ] ); } );
A schedule of your own, if hourly, twicedaily and daily are not enough:
register_cron_schedule( 'every_five_minutes', 5 * MINUTE_IN_SECONDS, __( 'Every five minutes', 'my-plugin' ) );
And at uninstall, the part that usually gets forgotten:
unregister_cron_jobs();
Action Scheduler
WP-Cron keeps no record of what ran and retries nothing. Action Scheduler
keeps a table of every action and a screen under Tools → Scheduled Actions.
Scheduler is the half every plugin writes for itself: one instance per
group, named for the plugin. The group keeps your actions apart from
everybody else's and is what uninstall clears, so never rename it once
shipped — actions queued under the old name are orphaned.
Loading it
Bundle woocommerce/action-scheduler (not prefixed: its entry file decides
which of several bundled copies wins) and require it from your main plugin
file, as the file is read:
// my-plugin.php, top level -- not inside a hook. use ArrayPress\RegisterCron\Scheduler; require __DIR__ . '/vendor-prefixed/autoload.php'; Scheduler::load( __DIR__ . '/libraries/woocommerce/action-scheduler/action-scheduler.php', __DIR__ . '/vendor/woocommerce/action-scheduler/action-scheduler.php' );
Action Scheduler registers itself on plugins_loaded at priority 0 and starts
at 1. Required from a plugin that boots on plugins_loaded at 10, both
moments have passed: it never starts, its functions never exist, and nothing
says so. Scheduler::available() tells you whether it is running.
Work that must not happen during a save
$queue = Scheduler::group( 'myplugin' ); // Every request, where the plugin boots. $queue->job( 'myplugin_sync_product', [ Sync::class, 'product' ] ); // In the save handler. $queue->defer( 'myplugin_sync_product', $product_id );
Saving three times in a minute queues one job; the one that runs reads the
database as it is then. The action's arguments are [ $id, $attempt ]. $id
may be a string — a remote reference for a job that outlives its row.
Retries
The job reports its own failure; the queue decides whether there is another
go, waits as stated, and calls gave_up once when it is over:
$queue = Scheduler::group( 'myplugin', [ 'retry' => [ 60, 300, 900, 3600, 21600 ], // waits after each failure 'attempts' => 5, 'gave_up' => function ( WP_Error $error, $id, int $attempt, array $context ) { myplugin_log( "{$context['label']} did not sync: {$error->get_error_message()}" ); }, ] ); function myplugin_sync_product( $id, $attempt ) { $result = Api::push( $id ); if ( is_wp_error( $result ) ) { Scheduler::group( 'myplugin' )->failed( 'myplugin_sync_product', $id, $attempt, $result, [ 'label' => get_the_title( $id ) ] ); } }
By default a failure with no response, a 429 or a 5xx (read from the
WP_Error's status data) is retried and anything else is given up on at
once. Pass retry_if to judge errors yourself, per group or per job, and
retry may be any object with exhausted( $attempt ) and delay( $attempt )
— arraypress/wp-webhooks' RetryPolicy is one.
Single actions
$queue->later( 'myplugin_deliver', [ $endpoint_id, $body, 1 ], 60 ); // every call is its own $queue->once( 'myplugin_catalogue_changed', [], 60 ); // ten changes, one action
Both return false without a scheduler, so you decide what running it now
would mean.
Recurring jobs
$queue->recurring( 'myplugin_clear_out', DAY_IN_SECONDS, [ Cleanup::class, 'sweep' ] );
Attached now, put in the calendar once on init (Action Scheduler's store is
not ready before), first run an hour away ('first' => 0 for now).
At a time of day
A repeating action is a number of seconds, so "08:00 every Monday" drifts an
hour twice a year. at() books one action and books the next each time it
runs, worked out afresh in the site's timezone:
$queue->at( 'myplugin_send_summary', [ Summary::class, 'send' ], [ 'time' => '08:00', 'every' => [ 'weekly' => 'week:mon', 'monthly' => 'month:1' ], 'wanted' => fn(): string => Summary::enabled() ? Summary::frequency() : '', // '' is off 'option' => 'myplugin_summary_schedule', // remembers what is booked ] );
Rules are day, week:mon … week:sun and month:1 … month:31 (a month
without that date is skipped). The booking's one argument is the key. The
calendar is put level with wanted on admin and cron requests, and a booking
for a key no longer wanted fixes the calendar instead of running.
$queue->local( $hook )->ensure( true ) does it now, after a settings save.
Uninstall
Scheduler::group( 'myplugin' )->unschedule_all();
Only works when some copy of Action Scheduler is running at uninstall — the plugin being removed is not loaded then, so it is another plugin's copy or nothing.
Without Action Scheduler
A deferred job runs where it stands (worse than deferring, better than
dropping it) and is never retried in the same request. later(), once(),
recurring and time-of-day jobs do nothing and say so.
What it does not do
WordPress cron runs on traffic, not on time — a quiet site runs a "daily" job
late, and a job that must be punctual needs a real system cron hitting
wp-cron.php. Action Scheduler runs on WP-Cron too. Nothing here changes that.
Requirements
- PHP 8.3 or later
- WordPress 7.1 or later
- Action Scheduler 3.6 or later, for the
Schedulerhalf
License
GPL-2.0-or-later