Customizing the WP Schedule event

2019-07-15 14:07发布

Experts,

Currently in one of my wordpress plugins there is a cron which runs as per schedule below. wp_schedule_event( time(), 'hourly', 'w4pr_cron' ); I would like to change this to run every 5 minutes in a particular time range.

For E.g. The current code as you know will run once every hour in a day. (24 runs in a day). I would like this to run every 5 minutes between 5:00am and 6:30am (EST) only (18 runs in a day).

Any help appreciated!

Thanks Thomas

标签: wordpress
2条回答
Viruses.
2楼-- · 2019-07-15 14:15

You would first need to add the custom cron schedule for it to run every 5 minutes

 // Add cron interval of 60 seconds
function addCronMinutes($array) {
    $array['minute'] = array(
            'interval' => 60,
            'display' => 'Once a Minute',
    );
    return $array;
}
add_filter('cron_schedules','addCronMinutes');

However, to only allow it to run within the certain time frame without causing extra overhead you may be better off schedule each specific event.

The other option would be to put logic in the trigger to only run your functions during the specified time frame, but that would cause extra overhead on high traffic sites where the cron would be firing every 5 minutes.

查看更多
一夜七次
3楼-- · 2019-07-15 14:31

First create a custom interval, you can find more information about this here.

 add_filter( 'cron_schedules', 'cron_add_5min' );

 function cron_add_5min( $schedules ) {
    $schedules['5min'] = array(
        'interval' => 5*60,
        'display' => __( 'Once every five minutes' )
    );
    return $schedules;
 }

Make sure that you have unscheduled the event registered by the plugin:

wp_unschedule_event( next_scheduled_event( 'w4pr_cron' ), 'w4pr_cron' );

Next schedule an event with this interval of recurrence to begin at 5 AM:

if( time() > strtotime( 'today 5:00' ) )
    wp_schedule_event( strtotime( 'tomorrow 5:00' ), '5min', 'w4pr_cron' );
else
    wp_schedule_event( strtotime( 'today 5:00' ), '5min', 'w4pr_cron' );

w4pr_cron is not a function, but a hook which has functions attached to it. So what you want to do is make sure nothing happens when this hook is called on if the timestamp is not within your given time interval. So in functions.php or somewhere which will see it executed on every page load, put:

add_action( 'init', function() {
    $start = strtotime( 'today 5:00' );
    $end = strtotime( 'today 6:30' );
    if( !(time() > $start && time() < $end) ) remove_all_actions( 'w4pr_cron' );
}
查看更多
登录 后发表回答