php - 插件中的 wp_schedule_event() 未安排 cron 事件

标签 php wordpress plugins cron

我正在创建一个 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' );  
}

关于php - 插件中的 wp_schedule_event() 未安排 cron 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47249581/

相关文章:

javascript - 使用 Javascript 提交表单时发送 Javascript 数组

php - 从具有 "AUTO_INCREMENT"的字段中获取未使用的 id - mysql

php - 将数据从 latin1_swedish 转换为 utf-8

php - 切换数据库mysql中的所有二进制值

javascript - 如何使用 wordpress 网站的引导轮播删除移动版本中的第一张幻灯片

ruby-on-rails - 如何在 Rails 中控制 gems 与插件的加载顺序

Wordpress/Apache - 图像文件名中的 unicode 字符出现 404 错误

javascript - 脚本5007 : Unable to get value of the property 'SetReturnValue' : object is null or undefined

mysql - Win7 MInGW QT MySQL 程序尖叫 "cannot find -lqsqlmysqld";失踪的图书馆在哪里?

java - Maven Jar Plugin 和 Maven Source Plugin 有什么区别?