我正在创建一个 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 事件,我没有错误
最佳答案
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' );
}
关于php - 插件中的 wp_schedule_event() 未安排 cron 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47249581/