自定义 WP Schedule 事件 [英] Customizing the WP Schedule event

查看:50
本文介绍了自定义 WP Schedule 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

专家,

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

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.

例如如您所知,当前代码将在一天中每小时运行一次.(一天运行 24 次).我希望它仅在上午 5:00 到早上 6:30(美国东部标准时间)之间每 5 分钟运行一次(一天运行 18 次).

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).

感谢任何帮助!

谢谢托马斯

推荐答案

首先创建一个自定义的区间,可以找到更多关于这个此处.

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' );

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

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 不是一个函数,而是一个附加了函数的钩子.因此,如果时间戳不在给定的时间间隔内,您想要做的是确保在调用此挂钩时不会发生任何事情.所以在functions.php或在每个页面加载时都会执行的地方,输入:

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' );
}

这篇关于自定义 WP Schedule 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆