How can I change the frequency of a scheduled event?

I have declared a scheduled event in a plugin like this :

function shedule_email_alerts() {
    if ( !wp_next_scheduled( 'send_email_alerts_hook' ) ) {
        wp_schedule_event(time(), 'hourly', 'send_email_alerts_hook');
    }
}

Then i wanted to change the frequency to ‘daily’, by doing so, replacing the original function with :

Read More
function shedule_email_alerts() {
    if ( !wp_next_scheduled( 'send_email_alerts_hook' ) ) {
        wp_schedule_event(time(), 'daily', 'send_email_alerts_hook');
    }
}

But it seems that my event is still fired every hour. I use the Core control plugin to monitor CRON tasks and it still shows as ‘once per hour’

Related posts

Leave a Reply

3 comments

  1. It looks for me that you are adding this event only when there is no such event ‘send_email_alerts_hook’ scheduled yet. Try something like this and let me know if it workded.

    function shedule_email_alerts() {
        if ( !wp_next_scheduled( 'send_email_alerts_hook' ) ) {
            wp_schedule_event(time(), 'daily', 'send_email_alerts_hook');
        } else {
            wp_reschedule_event(time(), 'daily', 'send_email_alerts_hook');
        } 
    }
    

    The thing is that you will “rewrite” this event all the time, so it would be good to deactivate this function when it run first time.

    The best solution would be to check how those jobs are gathered and check if this event is already added. If so then check if recurrence is different – if so reschedule. You can find this function in wp-includes/cron.php line ~63

    function wp_schedule_event( $timestamp, $recurrence, $hook, $args = array()) {
        $crons = _get_cron_array();
        $schedules = wp_get_schedules();
    
        if ( !isset( $schedules[$recurrence] ) )
            return false;
    
        $event = (object) array( 'hook' => $hook, 'timestamp' => $timestamp, 'schedule' => $recurrence, 'args' => $args, 'interval' => $schedules[$recurrence]['interval'] );
        $event = apply_filters('schedule_event', $event);
    
        // A plugin disallowed this event
        if ( ! $event )
            return false;
    
        $key = md5(serialize($event->args));
    
        $crons[$event->timestamp][$event->hook][$key] = array( 'schedule' => $event->schedule, 'args' => $event->args, 'interval' => $event->interval );
        uksort( $crons, "strnatcasecmp" );
        _set_cron_array( $crons );
    }
    

    Good luck!

  2. Ok, I could solve the problem by using wp_clear_scheduled_hook()

    I commented out my schedule declaration and added wp_clear_scheduled_hook('send_email_alerts_hook') at the end. Then deactivate – reactivate my plugin, which removed my scheduled hook. Then removed wp_clear_scheduled_hook() and uncommented my code, now the schedule was set properly.