什么是 WP Cron? 它是WordPress的一套定时触发机制,可以循环调度任务执行。 比如定期发布新文章、定期查看版本等功能,都是通过这个实现的。
WP Cron 能为我们做什么? 我们可以周期性地更新和提交网站数据,在假期定期向读者发送贺卡或表格,...
WordPress定时任务方法列表请参考:WP-Cron Functions
WP-Cron 效率不高,但还是很方便好用。 相关功能的使用整理如下。
wp_get_schedule
通过钩子别名获取预定的钩子。 成功时返回循环类型(每小时、每天两次、每天...),失败时返回 false。
<?php wp_get_schedule( $hook, $args ) ?>
$hook:钩子别名
$args:hook对应的函数的参数数组(可选)
wp_get_schedules
WordPress 默认支持每小时、每天两次和每天循环类别。 通过这个函数我们可以得到所有这些循环循环数组。
<?php wp_get_schedules() ?>
默认情况下,上述方法获取的数组对象如下。
array('hourly' => array(
'interval' => 3600,
'display' => 'Once Hourly'
),
'twicedaily' => array(
'interval' => 43200,
'display' => 'Twice Daily'
),
'daily' => array(
'interval' => 86400,
'display' => 'Once Daily'
)
)
我们可以向 cron_schedules 过滤器添加更多类型。 添加示例如下:
add_filter('cron_schedules', 'cron_add_weekly');function cron_add_weekly( $schedules )
{
// Adds once weekly to the existing schedules.
$schedules['weekly'] = array(
'interval' => 604800, // 1周 = 60秒 * 60分钟 * 24小时 * 7天
'display' => __('Once Weekly')
);
return $schedules;
}
wp_next_scheduled
通过钩子别名获取预定编排的下一次运行时间,并以整数形式返回。 它通常用于确定是否已进行预定安排。
<?php $timestamp = wp_next_scheduled( $hook, $args ); ?>
$hook:钩子别名
$args:hook对应的函数的参数数组(可选)
wp_schedule_event
按照循环周期调度一个WordPress hook,在预定的时间触发hook对应的函数。
<?php wp_schedule_event($timestamp, $recurrence, $hook, $args); ?>
$timestamp:时间(整数)
$recurrence:重复类别(每小时,每天两次,每天,...)
$hook:钩子别名
$args:hook对应的函数的参数数组(可选)
wp_reschedule_event
根据周期重新安排一个 WordPress 钩子。 但是我发现这个方法不能正常使用。 Codex 非常草书。 如果有人知道如何使用它,请告诉我。
wp_unschedule_event
通过预定时间和钩子别名取消预定安排。
<?php wp_unschedule_event($timestamp, $hook, $args ); ?>
$timestamp:时间(整数)
$hook:钩子别名
$args:hook对应的函数的参数数组(可选)
wp_clear_scheduled_hook
通过钩子别名,去除预定编排的钩子。
<?php wp_clear_scheduled_hook( $hook ); ?>
$hook:钩子别名
wp_schedule_single_event
安排一个 WordPress 钩子,在预定的时间触发钩子对应的函数。 与 wp_schedule_event 不同的是,该方法只调度一个触发器,没有重复的预留。
<?php wp_schedule_single_event($timestamp, $hook); ?>
$timestamp:时间(整数)
$args:hook对应的函数的参数数组(可选)
查看WordPress计划任务列表
因为是定时任务,不能立即生效,我们如何查看这些任务进度表呢? 可以安装一个插件来提供帮助。 推荐使用比较轻量级的WP-Cron Dashboard(与Quick Comments作者相同),安装后可以在Tool->WP-Cron中打开控制面板进行安装。