WP CRON runs only the first time

OK, so I’ve tested your code and I’m pretty sure it can’t run even once… And here’s why…

If you’ll take a look at wp_schedule_event you’ll see this check at the top of the function:

if ( !isset( $schedules[$recurrence] ) )
    return false;

It means that you can’t schedule event with unknown recurrence.

So let’s go back to your code… What it does is:

  • adds your custom recurrence (using cron_schedules hook),
  • schedules an event with that recurrence during plugin activation.

Everything look good, right? Well, no – it does not.

Activation hook is fired during plugin activation. So that plugin is not working before the activation is run. So your custom recurrence is not registered. So… your hook is not scheduled. I’ve tested that and the result of wp_schedule_event in your activation hook is false, so the event is not scheduled.

So what to do?

Simple – don’t schedule your event on activation hook, if you want to use custom recurrence.

So here’s your safer code:

register_deactivation_hook(__FILE__, 'my_deactivation');
function my_deactivation() {
    wp_clear_scheduled_hook('cron_every_5_seconds');
}

function add_every_5_seconds_cron_schedule( $schedules ) {
    $schedules['every_5_seconds'] = array(
        'interval'  => 5,
        'display'   => __( 'Every 5 Seconds', 'textdomain' )
    );
    return $schedules;
}
add_filter( 'cron_schedules', 'add_every_5_seconds_cron_schedule' );

function schedule_my_cron_events() {
    if ( ! wp_next_scheduled( 'cron_every_5_seconds') ) {
        wp_schedule_event( time(), 'every_5_seconds', 'cron_every_5_seconds' );
    }
}
add_action( 'init', 'schedule_my_cron_events' );

function cron_every_5_seconds_action() {
    $value = 91;
    update_user_meta( $value + 1, 'from_cron', 'updated' );
}
add_action( 'cron_every_5_seconds', 'cron_every_5_seconds_action' );

PS. (but it may be important) There is one more flaw with your code, but maybe it’s just cause by some edits before posting here…

You won’t be able to check if your cron runs only once or many times. Your event action updates user meta. But the new value that is set is always equal 91. And since you use update_user_meta, only one such meta will be stored in the DB.

Leave a Comment