### Install mtdowling/cron-expression using Composer Source: https://github.com/woocommerce/action-scheduler/blob/trunk/lib/cron-expression/README.md To install the cron-expression library, add the package to your project's composer.json file under the 'require' section. This ensures the library is managed by Composer and available for autoloading. ```javascript { "require": { "mtdowling/cron-expression": "1.0.*" } } ``` -------------------------------- ### Plugin Activation: Schedule Recurring Actions (PHP) Source: https://context7.com/woocommerce/action-scheduler/llms.txt Demonstrates the recommended pattern for scheduling recurring background actions when a WordPress plugin is activated. It includes examples for hourly, daily, and weekly schedules, utilizing Action Scheduler functions to ensure actions are set up correctly. Dependencies include the Action Scheduler library. ```php query( "DELETE FROM {$wpdb->prefix}my_plugin_logs WHERE created < DATE_SUB(NOW(), INTERVAL 30 DAY)" ); } ); add_action( 'my_plugin_weekly_report', function() { // Generate and email weekly report $report_data = generate_weekly_report(); wp_mail( get_option( 'admin_email' ), 'Weekly Plugin Report', $report_data ); } ); ``` -------------------------------- ### Schedule Single Action with Arguments in PHP Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/usage.md This example demonstrates scheduling a single action with arguments passed as an array, which are unpacked into callback parameters for sending notifications. It requires defining the action with the correct argument count via add_action and uses as_schedule_single_action. Inputs include timestamp, hook, and argument array; outputs email via wp_mail. Limitation: Fixed argument count; variable args need custom handling. ```php // You must specify the number of arguments to be accepted (in this case, 2). add_action( 'purchase_notification', 'send_purchase_notification', 10, 2 ); // When scheduling the action, provide the arguments as an array. as_schedule_single_action( time(), 'purchase_notification', array( 'bob@foo.bar', 'Learning Action Scheduler (e-book)', ) ); // Your callback should accept the appropriate number of parameters (again, in this case, 2). function send_purchase_notification( $customer_email, $purchased_item ) { wp_mail( $customer_email, 'Thank you!', "You purchased $purchased_item successfully." ); } ``` -------------------------------- ### as_schedule_recurring_action() Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/api.md This function sets up a recurring action that runs at specified intervals starting from a given timestamp. It enables periodic tasks with customizable intervals in seconds. Suitable for ongoing background processes like cron jobs in WordPress. ```APIDOC ## as_schedule_recurring_action() ### Description Schedule an action to run repeatedly with a specified interval in seconds. ### Usage ```php as_schedule_recurring_action( $timestamp, $interval_in_seconds, $hook, $args, $group, $unique, $priority ); ``` ### Parameters - **$timestamp** (integer) - Required - The Unix timestamp representing the date you want the action to run. - **$interval_in_seconds** (integer) - Required - The recurring interval in seconds. - **$hook** (string) - Required - Name of the action hook. - **$args** (array) - Optional - Arguments to pass to callbacks when the hook triggers. Default: array(). - **$group** (string) - Optional - The group to assign this job to. Default: ''. - **$unique** (boolean) - Optional - Whether the action should be unique. Default: false. - **$priority** (integer) - Optional - Lower values take precedence over higher values. Defaults to 10, with acceptable values falling in the range 0-255. ### Return value (integer) the action's ID. Zero if there was an error scheduling the action. The error will be sent to error_log. ``` -------------------------------- ### Get Next Scheduled Action Time (WP-CLI) Source: https://context7.com/woocommerce/action-scheduler/llms.txt Retrieves the next scheduled execution time for a specific action using the WP-CLI command-line tool. This is useful for monitoring and debugging scheduled tasks. ```bash wp action-scheduler action next send_test_email ``` -------------------------------- ### Parse Cron Expressions and Get Run Dates in PHP Source: https://github.com/woocommerce/action-scheduler/blob/trunk/lib/cron-expression/README.md Demonstrates how to use the CronExpression::factory method to parse predefined schedules like '@daily' or complex custom expressions. It shows how to check if a cron job is due, retrieve the next and previous run dates, and calculate future run dates by skipping iterations. ```php isDue(); echo $cron->getNextRunDate()->format('Y-m-d H:i:s'); echo $cron->getPreviousRunDate()->format('Y-m-d H:i:s'); // Works with complex expressions $cron = Cron\CronExpression::factory('3-59/15 2,6-12 */15 1 2-5'); echo $cron->getNextRunDate()->format('Y-m-d H:i:s'); // Calculate a run date two iterations into the future $cron = Cron\CronExpression::factory('@daily'); echo $cron->getNextRunDate(null, 2)->format('Y-m-d H:i:s'); // Calculate a run date relative to a specific time $cron = Cron\CronExpression::factory('@monthly'); echo $cron->getNextRunDate('2010-01-12 00:00:00')->format('Y-m-d H:i:s'); ``` -------------------------------- ### Schedule Recurring Action on Plugin Activation in PHP Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/usage.md This code schedules a recurring action when the plugin is activated, ensuring it starts immediately if not already scheduled. It relies on the Action Scheduler library and WordPress's register_activation_hook. Inputs include the action hook name and interval; outputs a scheduled action that runs every hour. Limitation: Does not handle rescheduling if the action is lost post-activation. ```php /** * Schedule recurring action on plugin activation. */ function my_plugin_activate() { if ( ! as_has_scheduled_action( 'my_plugin_recurring_action' ) ) { as_schedule_recurring_action( time(), HOUR_IN_SECONDS, 'my_plugin_recurring_action' ); } } register_activation_hook( __FILE__, 'my_plugin_activate' ); ``` -------------------------------- ### Run Action Scheduler Queue Directly (PHP) Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/faq.md This snippet demonstrates how to directly initiate the Action Scheduler queue using its runner. It's useful when you want to bypass WP-Cron or trigger the queue manually. No external dependencies are required beyond the Action Scheduler library itself. ```php ActionScheduler::runner()->run(); ``` -------------------------------- ### WP CLI: Other Commands Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/wp-cli.md Utility commands for datastore, runner, status, and version information in Action Scheduler. ```APIDOC ## WP CLI action-scheduler [datastore|runner|status|version] ### Description Provides status, version, and management for datastore and runner components. ### Method WP CLI Command ### Endpoint action-scheduler [datastore|runner|status|version] ### Parameters Use --help for command-specific options. ### Request Example wp action-scheduler status ### Response #### Success Response Queue status or version details. #### Response Example Status: Pending: X, Complete: Y, Failed: Z ``` -------------------------------- ### Add Action Scheduler as Git Subtree Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/usage.md Incorporates the Action Scheduler library into your repository as a Git subtree under the specified prefix directory. This command imports the trunk branch into your project while maintaining a clean commit history through squashing. The resulting code will be available in the libraries/action-scheduler folder. ```bash git subtree add --prefix libraries/action-scheduler subtree-action-scheduler trunk --squash ``` -------------------------------- ### Get Next Scheduled Time with Action Scheduler (PHP) Source: https://context7.com/woocommerce/action-scheduler/llms.txt Retrieves the Unix timestamp of the next scheduled execution for a given hook, optionally filtered by arguments or group. Returns false if not scheduled or true if the action is currently running/async. Useful for conditional scheduling based on upcoming runs. ```php 456 ); $next_expiration = as_next_scheduled_action( 'expire_trial_subscription', $args ); // Check within group $next_sync = as_next_scheduled_action( 'hourly_data_sync', null, 'data-sync' ); // Conditional scheduling based on next run time $next_backup = as_next_scheduled_action( 'daily_database_backup' ); if ( false === $next_backup || $next_backup > strtotime( '+2 days' ) ) { // Schedule a backup if none exists or next one is too far away as_schedule_single_action( strtotime( '+1 hour' ), 'daily_database_backup', array( 'backup_type' => 'emergency' ) ); } // Returns: integer timestamp, true (if running/async), or false (if not scheduled) ``` -------------------------------- ### WP-CLI Action Creation Source: https://context7.com/woocommerce/action-scheduler/llms.txt This section demonstrates how to create scheduled actions using WP-CLI. ```APIDOC ## WP-CLI: action-scheduler action create ### Description Create scheduled actions via WP-CLI for testing and automation. ### Method CLI ### Endpoint wp action-scheduler action create [action-name] [schedule] ### Parameters #### Arguments - `action-name` (string) - The name of the action to create. - `schedule` (string) - The schedule for the action (e.g., 'now', '2025-12-25 09:00:00', 'hourly'). #### Options - `--args` (string) - JSON string containing arguments for the action. - `--group` (string) - The group to assign the action to. - `--unique` (boolean) - Whether to prevent duplicate actions. - `--priority` (integer) - The priority of the action. - `--cron` (string) - Cron schedule expression. - `--status` (string) - Status of the action (pending, complete). - `--per-page` (integer) - Number of actions to list. ### Request Example `wp action-scheduler action create send_test_email async --args='{"email":"test@example.com", "subject":"Test"}' --group=testing` ### Response #### Success Response (0) - No output on success. #### Error Response (non-zero) - Error message displayed on failure. ``` -------------------------------- ### WP CLI: Action Subcommands Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/wp-cli.md Additional subcommands for managing individual actions, such as creating, canceling, or listing them. Use 'wp action-scheduler action --help' for details on each. ```APIDOC ## WP CLI action-scheduler action [subcommand] ### Description Manages individual actions: cancel, create, delete, generate, get, list, next, run. ### Method WP CLI Command ### Endpoint action-scheduler action [cancel|create|delete|generate|get|list|next|run] ### Parameters Varies by subcommand; use --help for specifics. ### Request Example wp action-scheduler action list ### Response #### Success Response Action details or list based on subcommand. #### Response Example { "actions": [ { "id": 123, "hook": "example_hook" } ] } ``` -------------------------------- ### Load Action Scheduler Library in WordPress Plugin Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/usage.md Includes and initializes the Action Scheduler library within a WordPress plugin. This code must be executed before the plugins_loaded action with priority 0 to ensure proper version registration and initialization. The function plugin_dir_path() dynamically determines the correct file path relative to the current plugin file. ```php 12345 ), 'order-processing' ); // With priority and unique flag $action_id = as_enqueue_async_action( 'send_welcome_email', array( 'user_id' => 99, 'email' => 'user@example.com' ), 'email-notifications', true, // unique - prevents duplicate actions 5 // priority - lower values run first ); // Register callback to handle the action add_action( 'process_order_notification', function( $order_id ) { $order = wc_get_order( $order_id ); if ( $order ) { // Process notification wp_mail( $order->get_billing_email(), 'Order Confirmation', "Your order #{$order_id} has been received." ); error_log( "Processed notification for order {$order_id}" ); } }, 10, 1 ); // Returns: integer action ID (e.g., 1234) or 0 on error ``` -------------------------------- ### Increase Action Scheduler Runner Initialization Rate Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/perf.md Initiates additional queue runners to handle larger queues on powerful servers. Creates 5 loopback requests each time a queue begins processing. Requires careful server configuration as it can overload sites if misconfigured. ```php /** * Trigger 5 additional loopback requests with unique URL params. */ function eg_request_additional_runners() { // allow self-signed SSL certificates add_filter( 'https_local_ssl_verify', '__return_false', 100 ); for ( $i = 0; $i < 5; $i++ ) { $response = wp_remote_post( admin_url( 'admin-ajax.php' ), array( 'method' => 'POST', 'timeout' => 45, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => false, 'headers' => array(), 'body' => array( 'action' => 'eg_create_additional_runners', 'instance' => $i, 'eg_nonce' => wp_create_nonce( 'eg_additional_runner_' . $i ), ), 'cookies' => array(), ) ); } } add_action( 'action_scheduler_run_queue', 'eg_request_additional_runners', 0 ); /** * Handle requests initiated by eg_request_additional_runners() and start a queue runner if the request is valid. */ function eg_create_additional_runners() { if ( isset( $_POST['eg_nonce'] ) && isset( $_POST['instance'] ) && wp_verify_nonce( $_POST['eg_nonce'], 'eg_additional_runner_' . $_POST['instance'] ) ) { ActionScheduler_QueueRunner::instance()->run(); } wp_die(); } add_action( 'wp_ajax_nopriv_eg_create_additional_runners', 'eg_create_additional_runners', 0 ); ``` -------------------------------- ### Backward Compatible Recurring Action Scheduling in PHP Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/usage.md This approach schedules and maintains a recurring action with fallback for older Action Scheduler versions, using as_supports for compatibility checks. It adds hooks on init, preferring the ensure hook if available or running on admin requests otherwise. Inputs are action details; outputs ensured scheduling. Limitation: Admin fallback increases load on every admin page in unsupported versions. ```php /** * Schedules the plugin's recurring action if it is not already scheduled. */ function my_plugin_schedule_my_recurring_action() { if ( ! as_has_scheduled_action( 'my_plugin_recurring_action' ) ) { as_schedule_recurring_action( time(), HOUR_IN_SECONDS, 'my_plugin_recurring_action' ); } } /** * Add the hooks needed for my_plugin_schedule_my_recurring_action() so it can make sure our hook stays scheduled. */ add_action( 'init', function () { if ( function_exists( 'as_supports' ) && as_supports( 'ensure_recurring_actions_hook' ) ) { // Preferred: runs periodically in the background. add_action( 'action_scheduler_ensure_recurring_actions', 'my_plugin_schedule_my_recurring_action' ); } elseif ( is_admin() ) { // Fallback: runs on every admin request. my_plugin_schedule_my_recurring_action(); } } ); ``` -------------------------------- ### Update Action Scheduler Git Subtree Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/usage.md Fetches the latest changes from the Action Scheduler repository and updates the local subtree accordingly. This two-step process first retrieves updates from the remote trunk branch, then merges them into the prefixed directory using a squash merge. Execute these commands periodically to keep the library current with upstream releases. ```bash git fetch subtree-action-scheduler trunk git subtree pull --prefix libraries/action-scheduler subtree-action-scheduler trunk --squash ``` -------------------------------- ### Trigger Action Scheduler Queue with Hook (PHP) Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/faq.md This code shows how to trigger the Action Scheduler queue by using the `action_scheduler_run_queue` WordPress hook. This method allows Action Scheduler to manage the queue execution. It accepts an optional context identifier for more granular control. ```php do_action( 'action_scheduler_run_queue', $context_identifier ); ``` -------------------------------- ### Add Git Remote for Action Scheduler Subtree Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/usage.md Registers the Action Scheduler repository as a Git remote to enable subtree management. This command configures a named reference to the upstream repository, allowing subsequent subtree operations without specifying the full URL. The remote name 'subtree-action-scheduler' is used as a shortcut for future commands. ```bash git remote add -f subtree-action-scheduler https://github.com/woocommerce/action-scheduler.git ``` -------------------------------- ### Check Feature Support Source: https://context7.com/woocommerce/action-scheduler/llms.txt This endpoint verifies if a specific feature is supported by the current Action Scheduler version. It's useful for providing fallback behavior for older versions. ```APIDOC ## GET /api/feature-support ### Description Verify if a specific feature is supported by the current Action Scheduler version. ### Method GET ### Endpoint /api/feature-support/{feature} ### Parameters #### Path Parameters - `feature` (string) - The feature to check (e.g., 'ensure_recurring_actions_hook'). #### Query Parameters - None ### Request Example None ### Response #### Success Response (200) - `supported` (boolean) - True if the feature is supported, false otherwise. #### Response Example { "supported": true } ``` -------------------------------- ### Custom Action Scheduler Storage Implementation (PHP) Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/faq.md This PHP code illustrates how to implement a custom storage mechanism for Action Scheduler. It involves extending the `ActionScheduler_Store` abstract class and registering your custom class using the `action_scheduler_store_class` filter. This provides flexibility in how action data is persisted. ```php function eg_define_custom_store( $existing_storage_class ) { return 'My_Radical_Action_Scheduler_Store'; } add_filter( 'action_scheduler_store_class', 'eg_define_custom_store', 10, 1 ); ``` -------------------------------- ### Create Action Scheduler Actions Table (SQL) Source: https://github.com/woocommerce/action-scheduler/wiki/Schema-Definitions Defines the SQL structure for the `wp_actionscheduler_actions` table, which stores information about scheduled actions. It includes columns for action ID, hook, status, scheduling times, priority, arguments, schedule details, group ID, attempt counts, and claim ID. ```sql CREATE TABLE wp_actionscheduler_actions ( action_id bigint(20) unsigned NOT NULL auto_increment, hook varchar(191) NOT NULL, status varchar(20) NOT NULL, scheduled_date_gmt datetime NULL default '0000-00-00 00:00:00', scheduled_date_local datetime NULL default '0000-00-00 00:00:00', priority tinyint unsigned NOT NULL default '10', args varchar(191), schedule longtext, group_id bigint(20) unsigned NOT NULL default '0', attempts int(11) NOT NULL default '0', last_attempt_gmt datetime NULL default '0000-00-00 00:00:00', last_attempt_local datetime NULL default '0000-00-00 00:00:00', claim_id bigint(20) unsigned NOT NULL default '0', extended_args varchar(8000) DEFAULT NULL, PRIMARY KEY (action_id), KEY hook (hook(191)), KEY status (status), KEY scheduled_date_gmt (scheduled_date_gmt), KEY args (args(191)), KEY group_id (group_id), KEY last_attempt_gmt (last_attempt_gmt), KEY `claim_id_status_scheduled_date_gmt` (`claim_id`, `status`, `scheduled_date_gmt`) ); ``` -------------------------------- ### Query Scheduled Actions Source: https://context7.com/woocommerce/action-scheduler/llms.txt This endpoint allows you to find and retrieve scheduled actions matching specific criteria. You can filter by hook, date range, arguments, group, and more. ```APIDOC ## GET /api/scheduled-actions ### Description Find and retrieve scheduled actions matching specific criteria. ### Method GET ### Endpoint /api/scheduled-actions ### Parameters #### Path Parameters - None #### Query Parameters - `hook` (string) - Optional - Filter actions by hook. - `date` (integer) - Optional - Filter actions before this date (timestamp). - `date_compare` (string) - Optional - Comparison operator for the date (e.g., '<=', '>='). - `per_page` (integer) - Optional - Number of actions to return per page. - `orderby` (string) - Optional - Field to order results by. - `order` (string) - Optional - Sorting order (ASC or DESC). - `args` (string) - Optional - Filter actions by arguments. - `status` (string) - Optional - Filter actions by status (e.g., PENDING, COMPLETE). - `group` (string) - Optional - Filter actions by group. - `return_format` (string) - Optional - Return format (objects, arrays, or IDs). ### Request Example { "hook": "daily_report_generation", "status": "ActionScheduler_Store::STATUS_PENDING", "per_page": 10 } ### Response #### Success Response (200) - `actions` (array) - An array of action objects, arrays, or IDs based on the `return_format` parameter. #### Response Example { "actions": [ { "action_id": "123", "hook": "daily_report_generation", "status": "PENDING" } ] } ``` -------------------------------- ### Create Action Scheduler Claims Table (SQL) Source: https://github.com/woocommerce/action-scheduler/wiki/Schema-Definitions Defines the SQL structure for the `wp_actionscheduler_claims` table, used to manage claims for actions, preventing duplicate processing. It includes a claim ID and the creation date of the claim. ```sql CREATE TABLE wp_actionscheduler_claims ( claim_id bigint(20) unsigned NOT NULL auto_increment, date_created_gmt datetime NULL default '0000-00-00 00:00:00', PRIMARY KEY (claim_id), KEY date_created_gmt (date_created_gmt) ); ``` -------------------------------- ### as_enqueue_async_action() Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/api.md This function enqueues an action to run asynchronously as soon as possible. It allows specifying arguments, grouping, uniqueness, and priority for the scheduled job. Useful for non-blocking background tasks in WordPress. ```APIDOC ## as_enqueue_async_action() ### Description Enqueue an action to run one time, as soon as possible. ### Usage ```php as_enqueue_async_action( $hook, $args, $group, $unique, $priority ); ``` ### Parameters - **$hook** (string) - Required - Name of the action hook. - **$args** (array) - Optional - Arguments to pass to callbacks when the hook triggers. Default: array(). - **$group** (string) - Optional - The group to assign this job to. Default: ''. - **$unique** (boolean) - Optional - Whether the action should be unique. Default: false. - **$priority** (integer) - Optional - Lower values take precedence over higher values. Defaults to 10, with acceptable values falling in the range 0-255. ### Return value (integer) the action's ID. Zero if there was an error scheduling the action. The error will be sent to error_log. ``` -------------------------------- ### WP CLI: action-scheduler migrate Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/wp-cli.md This command migrates Action Scheduler data to custom tables. It is only available during the migration process to update the database structure for better performance. ```APIDOC ## WP CLI action-scheduler migrate ### Description Migrates actions to custom database tables for improved scalability. ### Method WP CLI Command ### Endpoint action-scheduler migrate ### Parameters No specific options documented. ### Request Example wp action-scheduler migrate ### Response #### Success Response Migration progress and completion status. #### Response Example Migration completed: X actions moved. ``` -------------------------------- ### Create Action Scheduler Log Table (SQL) Source: https://github.com/woocommerce/action-scheduler/wiki/Schema-Definitions Defines the SQL structure for the `wp_actionscheduler_log` table, which records log messages for each action. It includes columns for log ID, the associated action ID, the log message, and timestamps for logging. ```sql CREATE TABLE wp_actionscheduler_log ( log_id bigint(20) unsigned NOT NULL auto_increment, action_id bigint(20) unsigned NOT NULL, message text NOT NULL, log_date_gmt datetime NULL default '0000-00-00 00:00:00', log_date_local datetime NULL default '0000-00-00 00:00:00', PRIMARY KEY (log_id), KEY action_id (action_id), KEY log_date_gmt (log_date_gmt) ); ``` -------------------------------- ### Implement Custom Action Scheduler Logger Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/faq.md This code snippet demonstrates how to register a custom logger class for Action Scheduler. It extends the abstract `ActionScheduler_Logger` class and uses a WordPress filter to inform Action Scheduler which class to use for logging. This allows for custom log storage and management. ```php function eg_define_custom_logger( $existing_storage_class ) { return 'My_Radical_Action_Scheduler_Logger'; } add_filter( 'action_scheduler_logger_class', 'eg_define_custom_logger', 10, 1 ); ``` -------------------------------- ### Schedule Single Action with Action Scheduler Source: https://context7.com/woocommerce/action-scheduler/llms.txt Schedules a one-time action to run at a specific future timestamp. Allows for unique actions and setting execution priority. Requires WordPress and Action Scheduler. Accepts a timestamp, hook name, arguments, group, unique flag, and priority. ```php 'sales', 'format' => 'pdf' ), 'reporting' ); // Schedule with unique flag to prevent duplicates $next_week = time() + ( 7 * DAY_IN_SECONDS ); $action_id = as_schedule_single_action( $next_week, 'expire_trial_subscription', array( 'subscription_id' => 456 ), 'subscriptions', true // unique ); // With priority for execution order $in_5_minutes = time() + 300; $action_id = as_schedule_single_action( $in_5_minutes, 'urgent_cache_clear', array( 'cache_key' => 'product_catalog' ), 'cache-maintenance', false, 1 // high priority ); // Implement the callback add_action( 'daily_report_generation', function( $report_type, $format ) { $data = generate_report_data( $report_type ); $file_path = create_pdf_report( $data, $format ); // Email to admin wp_mail( get_option( 'admin_email' ), "Daily {$report_type} Report", "Report attached.", array(), array( $file_path ) ); }, 10, 2 ); // Returns: integer action ID or 0 on error ``` -------------------------------- ### Enable Action Scheduler Data Store Migration in WordPress PHP Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/version3-0.md This PHP code adds a WordPress filter to enable migration from custom data stores in Action Scheduler. It requires Action Scheduler 3.0+ and WordPress. Input is the filter hook, output is enabling migration. Use only if migrating from custom stores. ```php add_filter( 'action_scheduler_migrate_data_store', '__return_true' ); ``` -------------------------------- ### Enqueue async action with Action Scheduler PHP Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/api.md Schedules an action to run once as soon as possible. Accepts hook name, arguments array, group, uniqueness flag, and priority parameters. Returns action ID or zero on error, with errors logged to error_log. ```php as_enqueue_async_action( $hook, $args, $group, $unique, $priority ); ``` -------------------------------- ### Schedule Cron Action (PHP) Source: https://context7.com/woocommerce/action-scheduler/llms.txt Schedules an action using cron expression syntax for complex timing patterns. It requires the run time, a cron string, the action hook, arguments, group, an optional unique flag, and priority. Callbacks are registered using add_action. ```php 'activity' ), 'email-digests' ); // Run every Sunday at midnight $action_id = as_schedule_cron_action( time(), '0 0 * * 0', // Sunday at midnight 'weekly_cleanup', array( 'clean_logs' => true, 'clean_cache' => true ), 'maintenance', true // unique ); // Run on the first day of every month at 3 AM $action_id = as_schedule_cron_action( time(), '0 3 1 * *', 'monthly_billing_process', array( 'billing_cycle' => 'monthly', 'auto_renew' => true ), 'billing', true, 10 // priority ); // Run every 15 minutes $action_id = as_schedule_cron_action( time(), '*/15 * * * *', 'check_external_api', array( 'service' => 'weather_api' ), 'api-monitoring' ); // Implement cron callback add_action( 'weekly_cleanup', function( $clean_logs, $clean_cache ) { if ( $clean_logs ) { global $wpdb; $wpdb->query( "DELETE FROM {$wpdb->prefix}actionscheduler_logs WHERE log_date < DATE_SUB(NOW(), INTERVAL 30 DAY)" ); } if ( $clean_cache ) { wp_cache_flush(); } error_log( 'Weekly cleanup completed at ' . current_time( 'mysql' ) ); }, 10, 2 ); // Returns: integer action ID or 0 on error ?> ``` -------------------------------- ### Create Action Scheduler Groups Table (SQL) Source: https://github.com/woocommerce/action-scheduler/wiki/Schema-Definitions Defines the SQL structure for the `wp_actionscheduler_groups` table, which organizes actions into logical groups. It includes a group ID and a slug for identifying the group. ```sql CREATE TABLE wp_actionscheduler_groups ( group_id bigint(20) unsigned NOT NULL auto_increment, slug varchar(255) NOT NULL, PRIMARY KEY (group_id), KEY slug (slug(191)) ); ``` -------------------------------- ### WP CLI: action-scheduler run Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/wp-cli.md Runs pending actions from the queue in batches, with options to filter by hooks or groups. It is recommended for processing large queues without WP Cron limitations, and can be forced to override concurrency limits. ```APIDOC ## WP CLI action-scheduler run ### Description Executes scheduled actions in batches, suitable for long-running or large-scale tasks. ### Method WP CLI Command ### Endpoint action-scheduler run ### Parameters #### Options (Query-like Parameters) - **--batch-size** (integer) - Optional - Actions to run per batch. Default: 100. - **--batches** (integer) - Optional - Number of batches. Default: 0 (unlimited). - **--hooks** (string) - Optional - Specific hooks, comma-separated. - **--group** (string) - Optional - Specific group to process. - **--exclude-groups** (string) - Optional - Groups to ignore, comma-separated. - **--force** (boolean) - Optional - Override concurrency limits. ### Request Example wp action-scheduler run --hooks=woocommerce_scheduled_subscription_payment --batch-size=200 --force ### Response #### Success Response Batch processing output with actions run count. #### Response Example Ran X actions in Y batches. ``` -------------------------------- ### Schedule single action with Action Scheduler PHP Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/api.md Schedules an action to run once at a specific Unix timestamp. Requires timestamp and hook name, plus optional arguments, group, uniqueness, and priority parameters. Returns action ID or zero on error, with errors logged. ```php as_schedule_single_action( $timestamp, $hook, $args, $group, $unique, $priority ); ``` -------------------------------- ### Schedule Recurring Action (PHP) Source: https://context7.com/woocommerce/action-scheduler/llms.txt Schedules an action to run repeatedly at fixed intervals. It takes the run time, interval in seconds, action hook, arguments, and group as parameters. An optional 'unique' flag prevents duplicate recurring actions. Callbacks are implemented using add_action. ```php 'https://api.example.com/sync' ), 'data-sync' ); // Run every 30 minutes with unique flag $action_id = as_schedule_recurring_action( time(), 30 * MINUTE_IN_SECONDS, 'check_inventory_levels', array( 'threshold' => 10 ), 'inventory', true // prevents duplicate recurring actions ); // Daily backup starting at specific time $midnight_tonight = strtotime( 'tomorrow midnight' ); $action_id = as_schedule_recurring_action( $midnight_tonight, DAY_IN_SECONDS, 'daily_database_backup', array( 'backup_type' => 'full', 'retention_days' => 30 ), 'maintenance', true, 5 // priority ); // Implement recurring callback add_action( 'hourly_data_sync', function( $api_endpoint ) { $response = wp_remote_get( $api_endpoint, array( 'timeout' => 30, 'headers' => array( 'Authorization' => 'Bearer ' . get_option( 'api_token' ) ) ) ); if ( is_wp_error( $response ) ) { error_log( 'Data sync failed: ' . $response->get_error_message() ); return; } $data = json_decode( wp_remote_retrieve_body( $response ), true ); update_option( 'last_sync_data', $data ); update_option( 'last_sync_time', time() ); }, 10, 1 ); // Returns: integer action ID or 0 on error ?> ``` -------------------------------- ### Schedule recurring action with Action Scheduler PHP Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/api.md Schedules an action to run repeatedly at specified intervals in seconds. Requires timestamp, interval, and hook name, plus optional arguments, group, uniqueness, and priority parameters. Returns action ID or zero on error. ```php as_schedule_recurring_action( $timestamp, $interval_in_seconds, $hook, $args, $group, $unique, $priority ); ``` -------------------------------- ### WP CLI: action-scheduler clean Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/wp-cli.md This command cleans up actions based on status, age, and batch settings. It is useful for removing completed, canceled, or failed actions to maintain queue efficiency. Default behavior processes canceled and complete actions older than 31 days. ```APIDOC ## WP CLI action-scheduler clean ### Description Cleans actions from the queue by status and age in batches to prevent overload. ### Method WP CLI Command ### Endpoint action-scheduler clean ### Parameters #### Options (Query-like Parameters) - **--batch-size** (integer) - Optional - Number of actions per status to clean in a single batch. Default: 20. - **--batches** (integer) - Optional - Number of batches to process. Default: 0 (unlimited). - **--status** (string) - Optional - Specific statuses to process, comma-separated. Default: canceled,complete. - **--before** (string) - Optional - Actions older than this date/time. Default: 31 days ago. - **--pause** (integer) - Optional - Seconds to pause between batches. Default: none. ### Request Example wp action-scheduler clean --status=complete --before='7 days ago' --batch-size=50 ### Response #### Success Response Command processes batches and outputs progress, e.g., actions cleaned count. #### Response Example Batch 1 of X cleaned: Y actions. ``` -------------------------------- ### as_schedule_single_action() Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/api.md This function schedules a single action to execute at a specific future timestamp. It supports grouping and uniqueness to manage scheduled tasks effectively. Ideal for one-off delayed operations in WordPress plugins. ```APIDOC ## as_schedule_single_action() ### Description Schedule an action to run one time at some defined point in the future. ### Usage ```php as_schedule_single_action( $timestamp, $hook, $args, $group, $unique, $priority ); ``` ### Parameters - **$timestamp** (integer) - Required - The Unix timestamp representing the date you want the action to run. - **$hook** (string) - Required - Name of the action hook. - **$args** (array) - Optional - Arguments to pass to callbacks when the hook triggers. Default: array(). - **$group** (string) - Optional - The group to assign this job to. Default: ''. - **$unique** (boolean) - Optional - Whether the action should be unique. Default: false. - **$priority** (integer) - Optional - Lower values take precedence over higher values. Defaults to 10, with acceptable values falling in the range 0-255. ### Return value (integer) the action's ID. Zero if there was an error scheduling the action. The error will be sent to error_log. ``` -------------------------------- ### Clean Failed Action Scheduler Actions Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/perf.md Removes old failed actions from Action Scheduler. Provides two approaches: filtering cleaner statuses or using WP CLI commands. The WP CLI method allows batch processing with time-based filtering. ```php add_filter( 'action_scheduler_default_cleaner_statuses', function( $statuses ) { $statuses[] = ActionScheduler_Store::STATUS_FAILED; return $statuses; } ); ``` ```shell wp action-scheduler clean --status=failed --batch-size=50 --before='90 days ago' --pause=2 ``` -------------------------------- ### Check Action Scheduler Feature Support Source: https://github.com/woocommerce/action-scheduler/blob/trunk/docs/api.md Determines if a given feature is supported by the current version of Action Scheduler. This is useful for ensuring compatibility when using specific hooks or functionalities. Currently, it supports checking for 'ensure_recurring_actions_hook'. ```php if ( as_supports( 'ensure_recurring_actions_hook' ) ) { // Safe to depend on the 'action_scheduler_ensure_recurring_actions' hook. add_action( 'action_scheduler_ensure_recurring_actions', 'my_plugin_schedule_my_recurring_action' ); } ```