0

I'm trying to run a function on an hourly basis with wp_schedule_event. I'm using the following code:

/* Add FB Sync schedule */
register_activation_hook(__FILE__, 'cp_fb_schedule');

// Scheduled Action Hook
function cp_fb_scheduled_sync( ) {
//      run the function
}

// Schedule Cron Job Event
function cp_fb_schedule() {
    if ( ! wp_next_scheduled( 'cp_fb_scheduled_sync' ) ) {
        wp_schedule_event( time(), 'hourly', 'cp_fb_scheduled_sync' );
    }
}
add_action( 'wp', 'cp_fb_schedule' );

register_deactivation_hook(__FILE__, 'my_deactivation');

function my_deactivation() {
    wp_clear_scheduled_hook('cp_fb_scheduled_sync');
}

I have checked with wp_next_scheduled and can see that the event is scheduled and the next one is due an hour after the last. So that appears to be working. The function I am trying to run works fine when I call it directly within a page (I've omitted the code here just so it's easier to read). It just doesn't run on schedule.

Can anyone work out what I'm doing wrong?

thanks

2
  • The action will trigger when someone visits your WordPress site, if the scheduled time has passed. Commented Nov 22, 2017 at 15:40
  • Hi @Drupalizeme, I've tried visiting the website myself and it hasn't run the function. I've just edited the function to make it a simple wp_mail to make sure it wasn't overcomplication with the function itself. This still doesn't work as scheduled. The wp_schedule_event code is a sub-folder of a plugin, if that makes a difference.
    – chris_huh
    Commented Nov 22, 2017 at 18:47

1 Answer 1

1

I have refactored the code and tested so this should put you in the right direction! But what I changed? I add the action hook cp_fb_scheduled_sync and set it to call it hourly this only needs to run one time and the WP knows the intervals.

/* Add FB Sync schedule */
register_activation_hook(__FILE__, 'cp_fb_schedule');

// Scheduled Action Hook
function cp_fb_scheduled_sync_function( ) {
//      run the function
}

// Schedule Cron Job Event
function cp_fb_schedule() {
    if ( ! wp_next_scheduled( 'cp_fb_scheduled_sync' ) ) {
        wp_schedule_event( time(), 'hourly', 'cp_fb_scheduled_sync' );
    }
}
add_action( 'cp_fb_scheduled_sync', 'cp_fb_scheduled_sync_function' );

register_deactivation_hook(__FILE__, 'my_deactivation');

function my_deactivation() {
    wp_clear_scheduled_hook('cp_fb_scheduled_sync');
}
1
  • Ah, yes, that did it! I guess it was my action hook that was messed up. Thanks so much
    – chris_huh
    Commented Nov 22, 2017 at 22:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.