是否可以在30 - 60分钟之间随机启动WP-Cron ?
What i have
add_action('my_hourly_event', 'do_this_hourly');
function my_activation()
{
if(!wp_next_scheduled( 'my_hourly_event' ))
{
wp_schedule_event( current_time( 'timestamp' ), 'hourly', 'my_hourly_event');
}
}
add_action('wp', 'my_activation');
function do_this_hourly()
{
// do something
}
不幸的是,wp_schedule_event没有30分钟,只接受这些间隔:每小时、每天两次(12H)、每天(24H)。
在我看来,有一个可以随机改变的计划事件有点奇怪,也许你应该看看不同的实现。不讨论你的选择,我将提供一个可能的答案。
有插件与Wordpress cron系统挂钩,允许不同的时间间隔。
一个解决方案是每30分钟只设置一个cron,并有一个自定义函数随机执行或不执行。
if (rand(0,1)) { ....
例如:
- 30分钟后,函数将被执行(你有30分钟的时间)
- 再过30分钟,函数干脆跳过运行
- 将在接下来的30分钟内再次触发并执行(您有1小时的cron)。
这里的问题是在1小时(跳过1次之后)强制执行,因为您最终可能会跳过超过30分钟。这可以实现存储上次执行的值。
另一个解决方案是在几乎相同的时间有2个cron(30分钟和1小时),并有一个自定义函数,如果1小时没有运行,将触发30分钟,等等。
这是一个很好的Wordpress cronjob插件如果你需要将cron执行安全地存储在一个Wordpress表中,你可以使用Wordpress add_option函数,以及get_option和update_option来获取和更新它的值。在下面的代码中,我将使用激活钩子而不是wp
钩子,如果您的代码驻留在主题中,请随意使用after_switch_theme
…
你可以使用wp_schedule_single_event()
,并简单地添加一个事件随机发生在30-60分钟每次事件发生;)
/**
* Registers single event to occur randomly in 30 to 60 minutes
* @action activation_hook
* @action my_awesome_event
*/
function register_event() {
$secs30to60min = rand( 1800, 3600 ); // Getting random number of seconds between 30 minutes and an hour
wp_schedule_single_event( time() + $secs30to60min, 'my_awesome_event' );
}
// Register activation hook to add the event
register_activation_hook( __FILE__, 'register_event' );
// In our awesome event we add a event to occcur randomly in 30-60 minutes again ;)
add_action( 'my_awesome_event', 'register_event' );
/**
* Does the stuff that needs to be done
* @action my_awesome_event
*/
function do_this_in_awesome_event() {
// do something
}
// Doing stuff in awesome event
add_action( 'my_awesome_event', 'do_this_in_awesome_event' );