Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 39 ยท REST API and Integrations

Background Processing With Action Scheduler

Run slow WooCommerce work in the background with Action Scheduler: async and scheduled actions, recurring jobs, groups, claims, retries and large imports.

A shopper clicks "Place order" and expects a quick answer. Sending the order to a warehouse, regenerating a product feed or importing 20,000 products can each take many seconds, so none of them belongs inside that request. They belong in a background job: you record "please do this later", return immediately, and a worker does the job on its own time.

WooCommerce ships a job queue for exactly this: Action Scheduler. It is a library bundled with WooCommerce (many other plugins bundle it too, and the newest copy wins). This lesson shows how to enqueue, schedule and repeat work, how workers claim jobs, and how to handle failure. The real functions need WordPress, so they are read-only here. The runnable examples are plain PHP stand-ins that reproduce the queue logic, including retries. For the WordPress background, see Caching and WP-Cron.

Why not plain WP-Cron?

WP-Cron stores a list of events in a single option row and fires when someone visits the site. For a store that causes real problems:

  • The whole schedule lives in one serialized option. Thousands of events make every page load read and rewrite a huge value, and two requests can overwrite each other.
  • There is no per-job record. You cannot see which jobs are pending, which failed, or what the error was.
  • There is no claiming. Two overlapping cron runs can execute the same event twice.
  • There is no built-in logging, retry, or search.

Action Scheduler stores each job as its own row in custom tables (posts-based storage was replaced by dedicated tables, actionscheduler_actions and friends). Every job has a status, arguments, a group, and a log. You see them in the admin under WooCommerce > Status > Scheduled Actions.

Enqueueing and scheduling

The API is a handful of functions. Each one takes a hook name (an ordinary WordPress action name) and an array of arguments.

PHP
<?php
// 1. As soon as possible (picked up on the next runner pass).
as_enqueue_async_action(
    'acme_sync_order_to_erp',
    array( 'order_id' => 727 ),
    'acme-erp',   // group
    true          // unique: do nothing if an identical pending action exists
);

// 2. At a specific time (Unix timestamp).
as_schedule_single_action(
    time() + 15 * MINUTE_IN_SECONDS,
    'acme_send_review_request',
    array( 'order_id' => 727 ),
    'acme-reviews'
);

// 3. Repeatedly, every 6 hours.
if ( false === as_has_scheduled_action( 'acme_refresh_feed', array(), 'acme-feeds' ) ) {
    as_schedule_recurring_action( time(), 6 * HOUR_IN_SECONDS, 'acme_refresh_feed', array(), 'acme-feeds' );
}

// 4. Cron-style expression.
as_schedule_cron_action( time(), '0 3 * * *', 'acme_nightly_cleanup', array(), 'acme-maintenance' );

Then you write the worker as a normal hook callback. Action Scheduler calls it with the arguments you stored:

PHP
<?php
add_action( 'acme_sync_order_to_erp', function ( $order_id ) {
    $order = wc_get_order( $order_id );
    if ( ! $order ) {
        return; // order deleted meanwhile: nothing to do
    }
    // Call the ERP here. Throw an exception on failure.
} );

A few rules that save pain:

  • Pass IDs, not objects. Arguments are serialized to the database. Store order_id, then load a fresh order when the job runs; the order may have changed in between.
  • Register the callback on every request, not only in admin. The runner executes in whichever request picks up the queue.
  • Guard recurring schedules with as_has_scheduled_action() (called as_next_scheduled_action() in older versions) so each page load does not add another copy. Do it on init or a later hook, never before Action Scheduler has initialized.
  • Give every job a group such as your plugin slug. You can then list, cancel or inspect just your jobs with as_get_scheduled_actions() or as_unschedule_all_actions( 'hook', array(), 'group' ).

How the queue runs

An action moves through statuses: pending then in-progress then complete, failed or canceled. A queue runner does the moving. By default the runner is started by a WP-Cron event every minute and also by an asynchronous loopback request, so the queue keeps running even on quiet sites. Each run:

  1. Claims a batch of due pending actions (default batch size 25). A claim is a database marker that says "this runner owns these rows", so a second runner cannot take the same ones.
  2. Runs each action in turn, marking it in-progress, then complete or failed.
  3. Stops when the time limit (default 30 seconds) or memory limit is close, and releases the claim.
flowchart LR
  A["Your code<br/>as_enqueue_async_action"] --> B["pending row"]
  B --> C["Runner claims a batch"]
  C --> D["in-progress"]
  D -->|"callback returns"| E["complete"]
  D -->|"exception thrown"| F["failed"]
  F -.->|"your retry code"| B

A job is a database row. The runner claims it, runs your callback, and records success or failure.

You can tune the runner with filters such as action_scheduler_queue_runner_batch_size and action_scheduler_queue_runner_concurrent_batches. On busy stores it is common to turn off the loopback trigger and run the queue with a real server cron job and WP-CLI (wp action-scheduler run), which gives you predictable capacity.

Failure and retries

Here is the part that surprises people: Action Scheduler does not retry failed actions for you. If your callback throws an exception, the action is marked failed and the message is stored in its log. A function that merely returns early is treated as success.

So retry logic is yours to write. A good pattern is: catch the failure, count the attempt, and schedule a new single action with a growing delay, up to a limit.

PHP
<?php
add_action( 'acme_sync_order_to_erp', function ( $order_id, $attempt = 1 ) {
    try {
        acme_erp_push( $order_id );
    } catch ( Throwable $e ) {
        if ( $attempt >= 5 ) {
            wc_get_logger()->error( "ERP sync gave up for order $order_id: " . $e->getMessage(), array( 'source' => 'acme-erp' ) );
            throw $e; // marks this action failed, visible in the admin
        }
        $delay = 60 * ( 2 ** $attempt ); // 2, 4, 8, 16 minutes
        as_schedule_single_action( time() + $delay, 'acme_sync_order_to_erp', array( $order_id, $attempt + 1 ), 'acme-erp' );
    }
}, 10, 2 );

Make jobs idempotent: running the same job twice must not charge twice or create two shipments. Claims prevent most double runs, but a runner that dies mid-job leaves the action in-progress until a timeout resets it, and then it runs again. See Idempotency for the full technique. Also keep each job short, ideally a few seconds.

Large imports

To import 20,000 products, do not make one job that loops over them all. A loop that is too long times out and has no progress to resume from. Instead use the fan-out pattern: one job reads a chunk (say 100 rows), processes it, and enqueues the job for the next chunk with the new offset. Or enqueue one small job per row. Either way a failure affects one chunk, progress is visible in the admin, and the runner can pause between batches so the site stays responsive.

Two final notes. Completed actions are cleaned up after a retention period (31 days by default), so do not use the table as permanent history; write your own record if you need one. And never send secrets in action arguments, because they are stored in plain text and shown in the admin.

The runnable stand-in

The TryIts below are not Action Scheduler. They are small PHP queue simulations that mirror its behavior: rows with statuses, claims, and a failure path.

PHP A job queue with claims and statuses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The second claim never overlaps the first. That is the point of claims: parallel runners split the work instead of repeating it.

PHP Retry with exponential backoff, then give up

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

What is real: the hook-plus-arguments model, statuses, claims, and the rule that exceptions mean failure. What is the stand-in: the in-memory array (the real one is database tables), and the retry loop (in real code, each retry is a newly scheduled action).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when an Action Scheduler callback throws an exception?

    Action Scheduler records the failure but does not retry on its own. You write retry logic by scheduling a new action, or you replay the failed one by hand.
  2. 2. Why should job arguments contain an order ID rather than the order object?

    Arguments are serialized and kept until the job runs. Loading the order by ID at that moment avoids stale or oversized data.
  3. 3. What is the purpose of a claim?

    Claims stop two parallel runners from taking the same rows, which would run a job twice.
  4. 4. Which design is best for importing 20,000 products?

    Small chunks stay under time limits, show progress, and let a failure affect only one chunk.

Summary

  • Move slow or unreliable work out of the request into Action Scheduler jobs: as_enqueue_async_action(), as_schedule_single_action(), recurring and cron variants.
  • Jobs are database rows with a hook, arguments, a group and a status; a runner claims a batch, runs callbacks and records the result.
  • Pass IDs, register callbacks on every request, group your jobs, and guard recurring schedules against duplicates.
  • A thrown exception means failed; retries and backoff are your responsibility, and jobs must be idempotent.
  • Split big imports into small chunked jobs, and consider a real server cron for busy stores.

Next: Security for WooCommerce Extensions