自定义WP计划事件

ami*_*z27 2 wordpress

专家介绍,

目前在我的一个wordpress插件中有一个cron,按照下面的时间表运行.wp_schedule_event(time(),'hourly','w4pr_cron'); 我想将此更改为在特定时间范围内每5分钟运行一次.

对于Eg您知道的当前代码将在一天中每小时运行一次.(一天24次).我希望这只在每天上午5:00到早上6:30(美国东部时间)之间每5分钟运行一次(每天18次).

任何帮助赞赏!

谢谢托马斯

C. *_* E. 10

首先创建自定义间隔,您可以在此处找到有关此内容的更多信息.

 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;
 }
Run Code Online (Sandbox Code Playgroud)

确保您已预先安排了插件注册的事件:

wp_unschedule_event( next_scheduled_event( 'w4pr_cron' ), 'w4pr_cron' );
Run Code Online (Sandbox Code Playgroud)

接下来安排具有此重复间隔的事件从凌晨5点开始:

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' );
Run Code Online (Sandbox Code Playgroud)

w4pr_cron不是一个函数,而是一个附加了函数的钩子.因此,如果时间戳不在给定的时间间隔内,则要确保在调用此挂钩时没有任何反应.因此,在functions.php或将在每个页面加载时执行的某个地方,放入:

add_action( 'init', function() {
    $start = strtotime( 'today 5:00' );
    $end = strtotime( 'today 6:30' );
    if( !(time() > $start && time() < $end) ) remove_all_actions( 'w4pr_cron' );
}
Run Code Online (Sandbox Code Playgroud)