在WordPress中使用wp-cron插件来设置定时任务

(编辑:jimmy 日期: 2024/9/30 浏览:2)

PHP 本身是无法创建定时任务的,但是 WordPress 自带了一个伪定时任务(Cron) API,非常的方便好用,包括 WordPress 本身的定时发布文章都依赖于这个 API

WP Cron 是什么"htmlcode">

<"htmlcode">
<"htmlcode">
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

通过勾子别名, 获取预定安排的下一个运行时刻, 以整型返回. 常用于判断是否已经做了预定安排.

<"htmlcode">
<"htmlcode">
<"htmlcode">
if( !wp_next_scheduled( 'test' ) ) wp_schedule_event( current_time( 'timestamp' ), 'twicedaily', 'test' );

首先使用 wp_next_scheduled() 函数判断是否已经创建,如果没创建则创建一个定时任务。

把需要执行的代码挂载到 test 钩子上就行了。