插件开发文档

理解 WP-Cron 调度机制

💡 云策文档标注

概述

WP-Cron 使用基于间隔的调度来模拟系统 cron,而非传统 cron 的特定时间点调度。它通过指定首次任务时间和重复间隔(以秒为单位)来安排任务执行。

关键要点

  • WP-Cron 调度基于间隔(秒),而非固定时间点,例如每 300 秒(5 分钟)重复任务。
  • WordPress 提供默认间隔(如 hourly、twicedaily、daily、weekly),并支持通过过滤器添加自定义间隔。
  • 自定义间隔可通过 `cron_schedules` 过滤器实现,需定义 interval(秒)和 display 参数。

代码示例

add_filter( 'cron_schedules', 'example_add_cron_interval' );
function example_add_cron_interval( $schedules ) { 
    $schedules['five_seconds'] = array(
        'interval' => 5,
        'display'  => esc_html__( 'Every Five Seconds' ), );
    return $schedules;
}

注意事项

  • 所有间隔时间均以秒为单位指定。

📄 原文内容

Unlike a traditional system cron that schedules tasks for specific times (e.g. “every hour at 5 minutes past the hour”), WP-Cron uses intervals to simulate a system cron.

WP-Cron is given two arguments: the time for the first task, and an interval (in seconds) after which the task should be repeated. For example, if you schedule a task to begin at 2:00PM with an interval of 300 seconds (five minutes), the task would first run at 2:00PM and then again at 2:05PM, then again at 2:10PM, and so on, every five minutes.

To simplify scheduling tasks, WordPress provides some default intervals and an easy method for adding custom intervals.

The default intervals provided by WordPress are:

  • hourly
  • twicedaily
  • daily
  • weekly (since WP 5.4)

Custom Intervals

To add a custom interval, you can create a filter, such as:

add_filter( 'cron_schedules', 'example_add_cron_interval' );
function example_add_cron_interval( $schedules ) { 
    $schedules['five_seconds'] = array(
        'interval' => 5,
        'display'  => esc_html__( 'Every Five Seconds' ), );
    return $schedules;
}

This filter function creates a new interval that will allow us to run a cron task every five seconds.

Note: All intervals are in seconds.