wp_cron()
概述
wp_cron() 函数用于注册 _wp_cron() 在 'shutdown' 动作上运行,以优化定时任务执行性能。它通过将 cron 生成移至 'shutdown' 钩子,减少对 Time To First Byte (TTFB) 的影响,允许服务器在等待请求时向浏览器发送 HTML 文档。
关键要点
- wp_cron() 是一个包装函数,根据条件调用 _wp_cron() 或将其添加到动作钩子。
- 默认情况下,_wp_cron() 在 'shutdown' 动作上运行,除非启用了 ALTERNATE_WP_CRON,此时它可能在 'wp_loaded' 动作上运行。
- 此设计旨在避免 wp_remote_post() 超时问题,并提升页面加载性能。
- 从 WordPress 6.9.0 开始,回调从 'wp_loaded' 移至 'shutdown' 动作,除非 ALTERNATE_WP_CRON 启用。
代码示例
function wp_cron(): void {
if ( defined( 'ALTERNATE_WP_CRON' ) && ALTERNATE_WP_CRON ) {
if ( did_action( 'wp_loaded' ) ) {
_wp_cron();
} else {
add_action( 'wp_loaded', '_wp_cron', 20 );
}
} elseif ( doing_action( 'shutdown' ) ) {
_wp_cron();
} else {
add_action( 'shutdown', '_wp_cron' );
}
}注意事项
- 开发者不应直接调用 wp_cron(),而是使用 wp_schedule_event() 等函数来创建定时事件。
- 示例展示了如何安排一个每小时发送邮件的定时任务,通过 wp_schedule_event() 和 add_action() 实现。
Registers _wp_cron() to run on the ‘shutdown’ action.
Description
The spawn_cron() function attempts to make a non-blocking loopback request to wp-cron.php (when alternative cron is not being used). However, the wp_remote_post() function does not always respect the timeout and blocking parameters. A timeout of 0.01 may end up taking 1 second. When this runs at the ‘wp_loaded’ action, it increases the Time To First Byte (TTFB) since the HTML cannot be sent while waiting for the cron request to initiate. Moving the spawning of cron to the ‘shutdown’ hook allows for the server to flush the HTML document to the browser while waiting for the request.
Source
function wp_cron(): void {
if ( defined( 'ALTERNATE_WP_CRON' ) && ALTERNATE_WP_CRON ) {
if ( did_action( 'wp_loaded' ) ) {
_wp_cron();
} else {
add_action( 'wp_loaded', '_wp_cron', 20 );
}
} elseif ( doing_action( 'shutdown' ) ) {
_wp_cron();
} else {
add_action( 'shutdown', '_wp_cron' );
}
}
Changelog
| Version | Description |
|---|---|
| 6.9.0 | The _wp_cron() callback is moved from ‘wp_loaded’ to the ‘shutdown’ action, unless ALTERNATE_WP_CRON is enabled; the function now always returns void. |
| 5.7.0 | Functionality moved to _wp_cron() to which this becomes a wrapper. |
| 5.1.0 | Return value added to indicate success or failure. |
| 2.1.0 | Introduced. |
Skip to note 2 content
Codex
Example
You should not call
wp_cron()yourself, but it allows you to create scheduled events like this.if ( ! wp_next_scheduled( 'wpdocs_task_hook' ) ) { wp_schedule_event( time(), 'hourly', 'wpdocs_task_hook' ); } add_action( 'wpdocs_task_hook', 'wpdocs_task_function' ); // 'wpdocs_task_hook` is registered when the event is scheduled /** * Send an alert by email. */ function wpdocs_task_function() { wp_mail( 'your@email.com', 'Automatic email', 'Automatic scheduled email from WordPress.'); }