Clean-up Action Scheduler and its Logs

To automatically clean-up finished Action Scheduler Actions and its Logs, upload the following Code to mu-plugins in the wp-content Folder and name it “action-scheduler-cleanup.php”. Or download it here (Caution: This is the “old” version at the bottom of this post), directly.

Final Update

To accomodate everything, this code was revised and is now based on two functions. Firstly, add the following to your functions.php to reduce the retention period to 1 day (or other specified).

add_filter('action_scheduler_retention_period', function() {
    return 1 * DAY_IN_SECONDS;
});

// Include failed actions in cleanup
add_filter('action_scheduler_default_cleaner_statuses', function($statuses) {
    $statuses[] = 'failed';
    return $statuses;
});

// Increase cleanup batch size
add_filter('action_scheduler_cleanup_batch_size', function() {
    return 100;
});

Then, add the following plugin to your plugin directory. Download it directly here and upload it as a normal plugin. The two together now work to delete everything on a daily basis (or the number of days specified above).

– End of Update –

Update 2

A more simplistic version of this code is the following. You can use it either in your functions.php or in a custom plugin.

<?php
// Add this code to your theme's functions.php file or in a custom plugin

// Schedule the daily cleanup event
function schedule_action_scheduler_cleanup() {
    if (!wp_next_scheduled('daily_action_scheduler_cleanup')) {
        wp_schedule_event(time(), 'daily', 'daily_action_scheduler_cleanup');
    }
}
add_action('wp', 'schedule_action_scheduler_cleanup');

// Function to perform the cleanup
function perform_action_scheduler_cleanup() {
    global $wpdb;

    // Delete completed actions
    $wpdb->query("DELETE FROM {$wpdb->prefix}wpbh_actionscheduler_actions WHERE status = 'complete'");

    // Delete failed actions
    $wpdb->query("DELETE FROM {$wpdb->prefix}wpbh_actionscheduler_actions WHERE status = 'failed'");

    // Clean up associated logs
    $wpdb->query("DELETE FROM {$wpdb->prefix}wpbh_actionscheduler_logs WHERE action_id NOT IN (SELECT action_id FROM {$wpdb->prefix}wpbh_actionscheduler_actions)");
}
add_action('daily_action_scheduler_cleanup', 'perform_action_scheduler_cleanup');

// Cleanup function when the plugin is deactivated
function cleanup_scheduler_on_deactivation() {
    wp_clear_scheduled_hook('daily_action_scheduler_cleanup');
}
register_deactivation_hook(__FILE__, 'cleanup_scheduler_on_deactivation');

Update

The following code is more comprehensive and runs every hour. Also, it checks for scheduled, instead of completed, as some might not have been completed. In this example, the retention time is set to 1 day.

<?php
/**
 * Action Scheduler Cleanup
 *
 * Automatically cleans up completed tasks from Action Scheduler and its logs.
 */

// Don't execute if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Schedule the cleanup task
 */
function schedule_action_scheduler_cleanup() {
    if (!as_next_scheduled_action('action_scheduler_cleanup')) {
        as_schedule_recurring_action(time(), HOUR_IN_SECONDS, 'action_scheduler_cleanup');
    }
}
add_action('wp', 'schedule_action_scheduler_cleanup');

/**
 * Perform the cleanup task
 */
function perform_action_scheduler_cleanup() {
    global $wpdb;

    // Set the retention period (in days)
    $retention_period = 1;

    // Delete completed actions older than the retention period
    $deleted_actions = $wpdb->query($wpdb->prepare(
        "DELETE FROM {$wpdb->prefix}actionscheduler_actions
        WHERE status IN ('complete', 'canceled', 'failed')
        AND scheduled_date_gmt < DATE_SUB(NOW(), INTERVAL %d DAY)",
        $retention_period
    ));

    // Delete logs for actions that no longer exist
    $deleted_logs = $wpdb->query(
        "DELETE FROM {$wpdb->prefix}actionscheduler_logs
        WHERE action_id NOT IN (
            SELECT action_id
            FROM {$wpdb->prefix}actionscheduler_actions
        )"
    );

    // Log the cleanup results
    error_log(sprintf(
        '[Action Scheduler Cleanup] Deleted %d actions and %d logs. Current time: %s',
        $deleted_actions,
        $deleted_logs,
        current_time('mysql')
    ));
}
add_action('action_scheduler_cleanup', 'perform_action_scheduler_cleanup');

Additionally, you can now check, if the plugin works by adding this temporarily in your functions.php, f.ex. via Code Snippets.

perform_action_scheduler_cleanup();

To change the amount of days, go to this section

    // Set the retention period (in days)
    $retention_period = 30;

and change the number to any desired number of days. 30 = Retention period of 30 days.

The File should be here:

wp-content > mu-plugins > action-scheduler-cleanup.php

<?php
/**
 * Action Scheduler Cleanup
 *
 * Automatically cleans up completed tasks from Action Scheduler and its logs.
 */

// Don't execute if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Schedule the cleanup task
 */
function schedule_action_scheduler_cleanup() {
    if (!as_next_scheduled_action('action_scheduler_cleanup')) {
        as_schedule_recurring_action(strtotime('midnight tonight'), DAY_IN_SECONDS, 'action_scheduler_cleanup');
    }
}
add_action('wp', 'schedule_action_scheduler_cleanup');

/**
 * Perform the cleanup task
 */
function perform_action_scheduler_cleanup() {
    global $wpdb;

    // Set the retention period (in days)
    $retention_period = 30;

    // Delete completed actions older than the retention period
    $wpdb->query($wpdb->prepare(
        "DELETE FROM {$wpdb->prefix}actionscheduler_actions
        WHERE status = 'complete'
        AND scheduled_date_gmt < DATE_SUB(NOW(), INTERVAL %d DAY)",
        $retention_period
    ));

    // Delete logs for actions that no longer exist
    $wpdb->query(
        "DELETE FROM {$wpdb->prefix}actionscheduler_logs
        WHERE action_id NOT IN (
            SELECT action_id
            FROM {$wpdb->prefix}actionscheduler_actions
        )"
    );
}
add_action('action_scheduler_cleanup', 'perform_action_scheduler_cleanup');

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *