函数文档

wp_get_ready_cron_jobs()

💡 云策文档标注

概述

wp_get_ready_cron_jobs() 函数用于检索准备就绪的 cron 任务,即时间戳已过期的任务。它基于 _get_cron_array() 的结果进行筛选,并可通过过滤器进行自定义。

关键要点

  • 函数返回一个数组,包含时间戳已过期的 cron 任务数组。
  • 使用 pre_get_ready_cron_jobs 过滤器可以覆盖默认的检索逻辑,直接返回自定义数组。
  • 内部通过 _get_cron_array() 获取所有 cron 任务,并基于当前 GMT 时间进行筛选。
  • 该函数在 WordPress 5.1.0 版本中引入。

代码示例

function wp_get_ready_cron_jobs() {
    $pre = apply_filters( 'pre_get_ready_cron_jobs', null );
    if ( null !== $pre ) {
        return $pre;
    }
    $crons    = _get_cron_array();
    $gmt_time = microtime( true );
    $results  = array();
    foreach ( $crons as $timestamp => $cronhooks ) {
        if ( $timestamp > $gmt_time ) {
            break;
        }
        $results[ $timestamp ] = $cronhooks;
    }
    return $results;
}

注意事项

  • 过滤器 pre_get_ready_cron_jobs 允许开发者自定义返回的 cron 任务数组,若返回非 null 值,将跳过默认筛选逻辑。
  • 函数依赖于 _get_cron_array() 获取 cron 数据,确保 cron 系统已正确设置。
  • 时间戳比较基于 GMT 时间,使用时需注意时区设置。

📄 原文内容

Retrieves cron jobs ready to be run.

Description

Returns the results of _get_cron_array() limited to events ready to be run, ie, with a timestamp in the past.

Return

array[] Array of cron job arrays ready to be run.

Source

function wp_get_ready_cron_jobs() {
	/**
	 * Filter to override retrieving ready cron jobs.
	 *
	 * Returning an array will short-circuit the normal retrieval of ready
	 * cron jobs, causing the function to return the filtered value instead.
	 *
	 * @since 5.1.0
	 *
	 * @param null|array[] $pre Array of ready cron tasks to return instead. Default null
	 *                          to continue using results from _get_cron_array().
	 */
	$pre = apply_filters( 'pre_get_ready_cron_jobs', null );

	if ( null !== $pre ) {
		return $pre;
	}

	$crons    = _get_cron_array();
	$gmt_time = microtime( true );
	$results  = array();

	foreach ( $crons as $timestamp => $cronhooks ) {
		if ( $timestamp > $gmt_time ) {
			break;
		}

		$results[ $timestamp ] = $cronhooks;
	}

	return $results;
}

Hooks

apply_filters( ‘pre_get_ready_cron_jobs’, null|array[] $pre )

Filter to override retrieving ready cron jobs.

Changelog

Version Description
5.1.0 Introduced.