Skip to content

Instantly share code, notes, and snippets.

@thenbrent
Last active December 2, 2022 17:24
Show Gist options
  • Save thenbrent/974053a348eb7f3ea4c4cb827a39d2e7 to your computer and use it in GitHub Desktop.
Save thenbrent/974053a348eb7f3ea4c4cb827a39d2e7 to your computer and use it in GitHub Desktop.
WooCommerce 3.5 introduced a new scalable, traceable job queue. This queue can be leveraged by extensions for processing large sets of jobs in the background. The default handler can also be replaced for custom requirements.

Job Queue API

WooCommerce 3.5 introduced a new scalable, traceable job queue. This queue can be used by extensions and custom code to process large sets of jobs in the background, and track the lifecycle of those jobs. The default handler can also be replaced.

This guide explains how to use the queue APIs for adding jobs, and how to replace the default queue handler.

Jobs are Actions

For flexibility and simplicity, each job is defined by an action hook.

Using a hook allows for the jobs behaviour to be customised at runtime, and for any code running on a site to perform operations.

Usage

Job queue APIs can be used via the global WC()->queue() method.

WC()->queue() returns the job queue handler intialised via the WC_Queue::instance() singleton.

The methods available via WC()->queue() will always match the methods specified in WC_Queue_Interface.

Adding a Job to the Queue

To add an action hook to the queue, call WC()->queue()->add() passing in the action hook. The action hook will then be triggered as soon as it reaches the front of the queue in a queue processing request.

Scheduling a Job

The job queue supports scheduling jobs to run in the future, and optionally recur.

To schedule a job in the future, call:

  1. WC()->queue()->schedule_single(): to schedule an action to run just once at some time in the future.
  2. WC()->queue()->schedule_recurring(): to schedule an action to run indefinitely based on a defined interval denominated in seconds.
  3. WC()->queue()->schedule_cron(): to schedule an action that recurs on a cron-like schedule.

WC_Queue_Interface

Job queues handlers must implement methods specified in WC_Queue_Interface.

Methods

Name Description Accepted Args Return
add() Enqueue an action to run one time, as soon as possible. String $hook: The hook to trigger.
Array $args: Arguments to pass when the hook triggers.
String $group: The group to assign this job to.
string: The action ID.
schedule_single() Schedule an action to run once at some time in the future. Integer $timestamp When the job will run.
String $hook The hook to trigger.
Array $args Arguments to pass when the hook triggers.
String $group The group to assign this job to.
string: The action ID.
schedule_recurring() Schedule a recurring action based on an interval defined in seconds. Integer $timestamp When the first instance of the job will run.
Integer $interval_in_seconds How long to wait between runs.
String $hook The hook to trigger.
Array $args Arguments to pass when the hook triggers.
String $group The group to assign this job to.
string: The action ID.
schedule_cron() Schedule an action that recurs on a cron-like schedule. Integer $timestamp The schedule will start on or after this time.
String $cron_schedule A cron-link schedule string. @see http://en.wikipedia.org/wiki/Cron.
String $hook The hook to trigger.
Array $args Arguments to pass when the hook triggers.
String $group The group to assign this job to.
string: The action ID.
cancel() Dequeue the next scheduled instance of an action. Any recurring actions with a matching hook should also be cancelled, not just the next scheduled action. String $hook The hook that the job will trigger.
Array $args Args that would have been passed to the job.
String $group The group the job is assigned to (if any).
cancel_all() Dequeue all actions with a matching hook, not just the next scheduled action. String $hook The hook that the job will trigger.
Array $args Args that would have been passed to the job.
String $group The group the job is assigned to (if any).
get_next() Get the date and time for the next scheduled occurrence of an action. String $hook The hook that the job will trigger.
Array $args Filter to a hook with matching args that will be passed to the job when it runs.
String $group Filter to only actions assigned to a specific group.
WC_DateTime
search() Find scheduled actions based on search parameters. Array $args Possible arguments, with their default values. See below for more details.
String $return_format OBJECT, ARRAY_A, or ids.
Array of matching actions, if any.

WC_Queue_Interface::search() args

The WC_Queue_Interface::search() method accepts the following array keys for searching scheduled jobs:

  • 'hook' => '' - the name of the action that will be triggered.
  • 'args' => null - the args array that will be passed with the action.
  • 'date' => null - the scheduled date of the action. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime(). Used in UTC timezone.
  • 'date_compare' => '<=' - operator for testing "date". accepted values are '!=', '>', '>=', '<', '<=', '='.
  • 'modified' => null - the date the action was last updated. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime(). Used in UTC timezone.
  • 'modified_compare' => '<=' - operator for testing "modified". accepted values are '!=', '>', '>=', '<', '<=', '='.
  • 'group' => '' - the group the action belongs to.
  • 'status' => '' - 'complete' or 'pending'.
  • 'claimed' => null - TRUE to find claimed actions, FALSE to find unclaimed actions, a string to find a specific claim ID.
  • 'per_page' => 5 - Number of results to return.
  • 'offset' => 0.
  • 'orderby' => 'date' - accepted values are 'hook', 'group', 'modified', or 'date'.
  • 'order' => 'ASC'.

Example

The built-in WC_Action_Queue class provides an example implementation of WC_Queue_Interface.

Default Queue Handler - Action Scheduler

The default queue handler included in WooCommerce is Action Scheduler.

This library provides a number of features beyond the WC_Queue_Interface APIs, including:

  • WP CLI commands for processing large queues more efficiently by processing them outside the constraints of web requests; and
  • an administration screen for monitoring, debugging and manually triggering actions in the queue.

Custom Queue Handlers

To implement a custom job queue handler:

  1. create a class which implements WC_Queue_Interface
  2. add a callback that returns the name of this class on the 'woocommerce_queue_class' filter

This will then be the class used for all calls to WC()->queue() methods.

Usage Examples

Example: Enqueue a Webhook

To enqueue a webhook based on its ID, the following code is used in WooCommerce core:

WC()->queue()->add( 'woocommerce_deliver_webhook_async', array( 'webhook_id' => $webhook->get_id(), 'arg' => $arg ), 'woocommerce-webhooks' );

In this example:

  • 'woocommerce_deliver_webhook_async' is the action hook name to trigger when processing the job
  • array( 'webhook_id' => $webhook->get_id(), 'arg' => $arg ) is the data to pass callbacks on 'woocommerce_deliver_webhook_async'
  • 'woocommerce-webhooks' is the group for this job. Groups are explained later.

Example: Schedule a Daily Cleanup

To schedule a daily cleanup of logs, the following code can be used:

WC()->queue()->schedule_recurring( time(), DAY_IN_SECONDS, 'woocommerce_cleanup_logs' );

In this example:

  • time() is the timestamp the first time the action will be triggered
  • DAY_IN_SECONDS is the interval for triggering the action in future
  • 'woocommerce_cleanup_logs' is the action hook name to trigger when processing the job
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment