我在执行此操作时遇到困难,并检查了之前的问题,但它们似乎不起作用。
到目前为止,我已通过将以下内容添加到我的 wp-config.php 来禁用默认的 WordPress cron:
define('DISABLE_WP_CRON', true);
然后我尝试安排我的任务从我的插件主 php 文件中每 5 分钟运行一次:
function my_cron_schedules($schedules){
if(!isset($schedules["5min"])){
$schedules["5min"] = array(
'interval' => 5*60,
'display' => __('Once every 5 minutes'));
}
if(!isset($schedules["30min"])){
$schedules["30min"] = array(
'interval' => 30*60,
'display' => __('Once every 30 minutes'));
}
return $schedules;
}
add_filter('cron_schedules','my_cron_schedules');
function schedule_my_cron(){
wp_schedule_event(time(), '5min', 'fivemin_schedule_hook');
}
if(!wp_get_schedule('fivemin_schedule_hook')){
add_action('init', 'schedule_my_cron',10);
}
function fivemin_schedule_hook() {
get_feed();
}
所以上面的内容似乎是在数据库中安排我的事件,但是在检查 cron 计划时有 100 个条目:
<?php print_r(get_option('cron')); ?>
我还确保使用以下内容更新我的 crontab:
* * * * * wget -q -O - http://wordpress.com/wp-cron.php?doing_wp_cron
但是我的任务似乎没有运行,并且我担心这个 5 分钟作业的数据库中的条目数量。
每个条目如下所示:
Array ( [1524308364] => Array ( [fivemin_schedule_hook] => Array ( [40cd750bba9870f18aada2478b24840a] => Array ( [schedule] => 5min [args] => Array ( ) [interval] => 300 ) ) )
我尝试通过在尝试触发时回显 $hook 来调试 wp-cron.php,并且当我直接访问 wp-cron.php 时会显示我的钩子(Hook)。然而实际的功能似乎并没有启动。
最佳答案
试试这个:
替换这个:
function schedule_my_cron(){
wp_schedule_event(time(), '5min', 'fivemin_schedule_hook');
}
if(!wp_get_schedule('fivemin_schedule_hook')){
add_action('init', 'schedule_my_cron',10);
}
..这样:
function schedule_my_cron(){
// Schedules the event if it's NOT already scheduled.
if ( ! wp_next_scheduled ( 'my_5min_event' ) ) {
wp_schedule_event( time(), '5min', 'my_5min_event' );
}
}
// Registers and schedules the my_5min_event cron event.
add_action( 'init', 'schedule_my_cron' );
// Runs fivemin_schedule_hook() function every 5 minutes.
add_action( 'my_5min_event', 'fivemin_schedule_hook' );
//add_action( 'my_5min_event', 'another_function_to_call' );
//add_action( 'my_5min_event', 'another_function_to_call2' );
但更合适/首选的方法是将其添加到插件的激活函数中:
wp_schedule_event( time(), '5min', 'my_5min_event' );
示例:
register_activation_hook( __FILE__, 'my_plugin_activation' );
function my_plugin_activation() {
if ( ! wp_next_scheduled ( 'my_5min_event' ) ) {
wp_schedule_event( time(), '5min', 'my_5min_event' );
}
}
..将用于代替以下内容:
function schedule_my_cron(){
// Schedules the event if it's NOT already scheduled.
if ( ! wp_next_scheduled ( 'my_5min_event' ) ) {
wp_schedule_event( time(), '5min', 'my_5min_event' );
}
}
// Registers and schedules the my_5min_event cron event.
add_action( 'init', 'schedule_my_cron' );
并且将其添加到插件的停用函数中的某个位置:
wp_clear_scheduled_hook( 'my_5min_event' );
示例:
register_deactivation_hook( __FILE__, 'my_plugin_deactivation' );
function my_plugin_deactivation() {
wp_clear_scheduled_hook( 'my_5min_event' );
}
参见https://codex.wordpress.org/Function_Reference/wp_schedule_event#Examples了解更多详情。
关于wordpress - 在 WordPress 插件中直接设置 cron 作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49954871/