0

My plugin sets up a CRON job on plugin activation to run after every 5 minutes. I want to provide a section in my plugin settings page, where the user can specify an interval. How would I do it? I am using the cron_schedules filter to add a custom CRON schedule. I am thinking of using it to get the option value for the user set CRON interval. Is this the right way to do it? If not, then how should I do it?

Update:

//done in plugin activation
if ( !wp_next_scheduled( 'my_custom_event' ) ) {
    wp_schedule_event( time(), 'everyminute', 'my_custom_event' );
}

add_filter( 'cron_schedules', 'add_cron_schedule' );
add_action( 'my_custom_event',  'cron_data_update' );

//This is where I get the value set from the plugin settings
function add_cron_schedule( $schedules ) {
    $my_settings = get_option( 'my-settings' );
    $period = ( isset( $my_settings['my-cron-interval'] ) && $my_settings['my-cron-interval'] != '' ) ? $my_settings['my-cron-interval'] : 30;

    $schedules['everyminute'] = array(
        'interval' => MINUTE_IN_SECONDS * $period,
        'display' => __('My Schedule')
    );

    return $schedules;
}

function cron_data_update() {
    //do something
}

As you can see, I am getting the value set by the user via the plugin settings page. If nothing was set, I use 30 minutes as default. Is this the right way to do it?

3
  • edit your post to show the code you have tried even if it doesn't work
    – mmm
    Sep 21, 2015 at 13:36
  • Sure. It works actually, but I am not sure if that is the right way to do. Sep 22, 2015 at 5:56
  • @mmm Done. Please check. Sep 22, 2015 at 6:33

1 Answer 1

0

Yes, in my opinion that's exactly the right way to extend the default schedule timings. I would be a little more informative with the display value but I think that is only example code.

However, one important thing should be taken into account. The default WordPress schedule implementation that is invoked as a side effect of http requests will be effecting your sites performance even more if you reduce the time intervals of schedule executions. So you should move schedule execution to cron jobs at latest at this point. You can read in detail about that here: https://medium.com/write-better-wordpress-code/optimized-use-of-schedules-c18c3c1383e9

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.