WordPress scheduled tasks can publish content, process orders, send reminders, clear temporary data, or synchronize records without waiting for a visitor to click a button. This guide explains how to create and inspect WP-Cron events, choose between WP-Cron and server-side tools, prevent duplicate runs, handle failures, and troubleshoot missed or slow tasks safely.
Overview
WP-Cron is WordPress's built-in scheduling system. Despite its name, it is not the same as a continuously running operating-system cron daemon. WordPress checks for due events during site requests, then attempts to run them in the background. On a low-traffic site, a task may therefore run later than its scheduled time. On a busy site, many visitors can create more opportunities for scheduled work to start.
For small, non-urgent tasks, WP-Cron is often sufficient. For time-sensitive or resource-intensive processing, a real server cron job, Action Scheduler, or a queue-based architecture may be a better fit. The right choice depends on task volume, execution time, hosting access, and how much failure tracking the workflow requires.
WP-Cron compared with other options
| Approach | Best suited to | Important consideration |
|---|---|---|
| WP-Cron | Small recurring tasks in a typical plugin | Runs through WordPress requests and may be delayed when traffic is low. |
| Real server cron | Predictable triggering of WP-Cron or a custom command | Requires hosting or server access and careful command configuration. |
| Action Scheduler | Large sets of trackable actions, especially WooCommerce-related processing | Use its APIs and monitoring tools rather than treating it like a simple one-off hook. |
| Queue-based processing | High-volume, slow, retryable, or distributed workloads | Needs a worker, queue storage, observability, and a deployment plan. |
Before writing code, define the job's purpose, expected frequency, maximum work per run, acceptable delay, and recovery behavior. This short design step prevents a routine cleanup task from becoming an unbounded database or API operation.
Checklist by scenario
Scenario 1: Schedule a recurring event in a plugin
Register the schedule when the plugin is activated, check for an existing event before adding one, and connect the event to a callback. Keep the callback small enough to finish reliably.
<?php
function ccs_register_daily_sync() {
if ( ! wp_next_scheduled( 'ccs_daily_sync' ) ) {
wp_schedule_event( time() + 60, 'daily', 'ccs_daily_sync' );
}
}
register_activation_hook( __FILE__, 'ccs_register_daily_sync' );
add_action( 'ccs_daily_sync', 'ccs_run_daily_sync' );
function ccs_run_daily_sync() {
// Fetch a limited batch, process it, and record the result.
}
The first argument is a Unix timestamp for the first run. The second is a recurrence name such as hourly, twicedaily, or daily. The hook name must be unique to your plugin. If the callback needs arguments, pass them as the fourth argument and use the matching accepted-argument count in add_action().
Do not put scheduling logic only in a file that might not load on every request. Activation hooks are a clear place to create recurring events. For existing installations, include a small versioned migration that checks whether the event exists and creates or updates it when necessary.
Scenario 2: Add a custom interval
Use the cron_schedules filter when the built-in intervals do not match the workflow. The interval value is expressed in seconds, and the schedule name is the value passed to wp_schedule_event().
add_filter( 'cron_schedules', 'ccs_add_fifteen_minute_schedule' );
function ccs_add_fifteen_minute_schedule( $schedules ) {
$schedules['ccs_every_fifteen_minutes'] = array(
'interval' => 15 * MINUTE_IN_SECONDS,
'display' => 'Every fifteen minutes',
);
return $schedules;
}
function ccs_schedule_queue_check() {
if ( ! wp_next_scheduled( 'ccs_queue_check' ) ) {
wp_schedule_event(
time() + MINUTE_IN_SECONDS,
'ccs_every_fifteen_minutes',
'ccs_queue_check'
);
}
}
Choose an interval based on the work's actual requirement, not simply the shortest interval available. A frequent event that does nothing most of the time still creates database checks and operational noise.
Scenario 3: Run a task once
Use wp_schedule_single_event() for delayed work that should happen once, such as a follow-up after an import or a cleanup after a temporary process. Prevent duplicate single events when the same action might be requested repeatedly.
function ccs_schedule_cleanup( $record_id ) {
$timestamp = time() + 30 * MINUTE_IN_SECONDS;
wp_schedule_single_event(
$timestamp,
'ccs_cleanup_record',
array( (int) $record_id )
);
}
add_action( 'ccs_cleanup_record', 'ccs_cleanup_record_callback' , 10, 1 );
function ccs_cleanup_record_callback( $record_id ) {
$record_id = absint( $record_id );
if ( ! $record_id ) {
return;
}
// Confirm the record is still eligible before changing it.
}
If the same record can be queued more than once, store a job identifier or check existing scheduled arguments before adding another event. Design callbacks to be idempotent: running the same operation twice should not create duplicate records, send duplicate messages, or corrupt state.
Scenario 4: Remove events when a plugin is deactivated
Clean up recurring events in a deactivation hook. The hook name must match the one used when scheduling the event.
register_deactivation_hook( __FILE__, 'ccs_remove_scheduled_tasks' );
function ccs_remove_scheduled_tasks() {
wp_clear_scheduled_hook( 'ccs_daily_sync' );
wp_clear_scheduled_hook( 'ccs_queue_check' );
}
Use an uninstall routine separately if the plugin should remove stored settings or custom tables. Deactivation usually means “stop running,” while uninstall means “remove plugin data.” Keep those decisions distinct.
Scenario 5: Integrate with WooCommerce or a larger queue
For a small WooCommerce customization, a scheduled hook may be enough to process a limited set of records. For many orders, API requests, emails, or retries, use the platform's established queue mechanism where available. Action Scheduler is commonly encountered in WooCommerce environments and provides a model for storing, processing, and inspecting individual actions. Avoid replacing a queue with one WP-Cron callback that loops over every record in one request.
When your task is part of a custom content workflow, first define the data model and job status. The guidance in this WordPress content-modeling guide can help keep task records separate from presentation logic.
What to double-check
- Duplicate prevention: Use
wp_next_scheduled()before creating recurring events. Review activation and migration code so both cannot register competing hooks. - Callback scope: Process a bounded batch rather than loading every item. Store a cursor, page number, or last-processed identifier when the dataset can grow.
- Input safety: Validate IDs, sanitize values, check permissions where a task acts on user-controlled data, and use prepared database queries. Scheduled callbacks still need the same security discipline as admin or frontend code. See the WordPress security hardening checklist for a broader review.
- External requests: Set practical timeouts, handle non-success responses, and avoid making an unlimited number of remote requests in one run.
- Retries: Decide which failures are temporary. Track attempts and use a maximum retry count so a permanently invalid record does not run forever.
- Overlapping runs: A slow callback can still be running when another trigger starts. Use a short-lived lock, such as a transient or an option with an expiry, and release it in a controlled way. A lock is a guard, not a complete distributed queue.
- Time zones: WordPress settings, PHP time, and server time may differ. Store timestamps consistently and use WordPress date functions when displaying site-local times.
- Deployment: Test activation, deactivation, plugin updates, and rollback on staging. Include scheduled-event behavior in your release checklist; the staging update checklist is a useful companion.
For visibility, record a concise status such as last start, last success, last error, item count, and next intended run. Do not log sensitive payloads or credentials. A simple admin status screen or structured log can turn “the cron is broken” into a specific diagnosis.
Common mistakes
- Assuming scheduled means exact. WP-Cron events are due after a timestamp; they are not guaranteed to execute at that exact second. Use a real server cron trigger when predictable polling matters.
- Scheduling on every request. Calling
wp_schedule_event()unconditionally can create unnecessary work or confusing event state. Always check for an existing event. - Using one massive callback. Large loops increase timeout, memory, locking, and retry risks. Break the work into bounded batches or individual queue actions.
- Ignoring the return value. Where supported, pass
truefor the API's error-reporting argument and inspect the result during development. Log failures with enough context to reproduce them. - Forgetting that cron may be disabled. Some sites define
DISABLE_WP_CRONand rely on a hosting-level trigger. If that trigger is missing or points to the wrong site, events will accumulate without being processed. - Clearing the wrong hook. Cleanup only works when the deactivation hook name and any relevant arguments match the scheduled event. Inspect the event list before assuming cleanup succeeded.
- Mixing business logic with scheduling logic. Keep the callback responsible for processing and keep registration, migration, and cleanup separate. This makes plugin updates and tests safer. A review using the WordPress code review checklist can reveal these coupling problems.
When to revisit
Review scheduled tasks before seasonal planning cycles, major content imports, marketing campaigns, hosting migrations, and plugin or WordPress updates. Revisit them whenever the workflow, data volume, PHP environment, or queue tool changes. A task that worked for a small site may need batching or a dedicated worker after the site grows.
Use this practical review sequence:
- List every recurring and single event your custom code registers.
- Confirm each event has one intended callback, a clear interval, and an owner in the codebase.
- Inspect the next run, last result, duration, item count, and error log.
- Test a missed trigger, a failed external request, an empty dataset, and a duplicate trigger on staging.
- Check whether the hosting setup uses normal WP-Cron or a server-side trigger, especially after migration.
- Confirm deactivation and upgrade paths do not leave obsolete hooks behind.
- Document the task's retry limit, lock behavior, and manual recovery procedure.
If WordPress cron is not running, start with fundamentals: confirm that events exist, check whether cron is disabled, inspect site and server logs, verify loopback or scheduled-request behavior, and look for fatal errors or blocked HTTP requests. Then run the callback with a small, safe test batch. For production systems that require dependable processing, move from a single WP-Cron callback to a server-triggered or queue-based workflow rather than adding more frequent polling.
Finally, keep the implementation maintainable. Put custom scheduling code in a focused plugin rather than a theme when the task supports site functionality. The maintainable custom plugin checklist provides a useful structure for versioning, testing, and release management.