我正在创建一个WordPress插件,当插件被激活时,我需要安排一个cron作业,每5分钟运行一次.
这是我的代码;
// Register plugin activation hook
function my_plugin_activate() {
if( !wp_next_scheduled( 'my_function_hook' ) ) {
wp_schedule_event( time(),'5','my_function_hook' );
}
}
register_activation_hook( __FILE__,'my_plugin_activate' );
// Register plugin deactivation hook
function my_plugin_deactivate(){
wp_clear_scheduled_hook('my_function_hook');
}
register_deactivation_hook(__FILE__,'my_plugin_deactivate');
// Function I want to run when cron event runs
function my_function(){
//Function code
}
add_action( 'my_function_hook','my_function');
当我使用这个插件https://wordpress.org/plugins/wp-crontrol/检查cron事件时,没有添加任何内容,我期待添加一个以5分钟为间隔运行’my_function’的cron事件,我没有错误
见:
wp_schedule_event()
Valid values for the recurrence are hourly,daily,and twicedaily.
These can be extended using the ‘cron_schedules’ filter in
wp_get_schedules().
因此,您只需添加每5分钟运行一次的自定义计划.
<?php // Requires PHP 5.4+.
add_filter( 'cron_schedules',function ( $schedules ) {
$schedules['every-5-minutes'] = array(
'interval' => 5 * MINUTE_IN_SECONDS,'display' => __( 'Every 5 minutes' )
);
return $schedules;
} );
if( ! wp_next_scheduled( 'my_function_hook' ) ) {
wp_schedule_event( time(),'every-5-minutes','my_function_hook' );
}
