如何使用调度挂钩运行wordpress cron作业



我需要使用wp函数运行一个自定义cron作业。我试着遵循这个答案,但下面的文章没有运行。

我不需要每5分钟运行一次wp_remote_get

在function.php中我做:

$args = array(false);
function schedule_my_cron(){
wp_schedule_event(time(), '5min', 'my_schedule_hook', $args);
}
if(!wp_next_scheduled('my_schedule_hook',$args)){
add_action('init', 'schedule_my_cron');
}
function my_schedule_hook() {
wp_remote_get('https://example.com/wp-content/themes/JikuHealth/scripts/covid-19_global_data.php');
}

wp文档在这里,但我仍然不明白如何。

默认支持的重复次数为"每小时"、"每两次"、"每天"one_answers"每周"。你正在使用"5分钟",但你已经创建了吗?这是一个例子:

function custom_cron_schedule( $schedules ) {
$schedules['5min'] = array('interval' => 5 * MINUTE_IN_SECONDS, 'display' => 'Every 5 minutes');
return $schedules;
}
add_filter( 'cron_schedules', 'custom_cron_schedule' );

编辑

示例的完整代码

// Your custom recurrences: '5min' , '20min'
function custom_cron_schedule( $schedules ) {
if(!isset($schedules['5min'])){
$schedules['5min'] = array(
'interval' => 5 * MINUTE_IN_SECONDS,
'display' => __('Once every 5 minutes'));
}
if(!isset($schedules['20min'])){
$schedules['20min'] = array(
'interval' => 20 * MINUTE_IN_SECONDS,
'display' => __('Once every 20 minutes'));
}
return $schedules;
}
add_filter( 'cron_schedules', 'custom_cron_schedule' );
// Your function
function my_schedule_hook() {
//do your stuff
wp_remote_get('https://example.com/wp-content/themes/JikuHealth/scripts/covid-19_global_data.php');
}
// Schedule Cron Job Event
if (!wp_next_scheduled('name_your_cron')) {
//You can now use '5min', '20min' or any of the default here
wp_schedule_event( time(), '5min', 'name_your_cron' );
}
add_action( 'name_your_cron', 'my_schedule_hook' ); 

最新更新