wp_cron()

Run scheduled callbacks or spawn cron for all scheduled events.


Description Description

Warning: This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. For information about casting to booleans see the PHP documentation. Use the === operator for testing the return value of this function.


Return Return

(bool|int) On success an integer indicating number of events spawned (0 indicates no events needed to be spawned), false if spawning fails for one or more events.


Top ↑

Source Source

File: wp-includes/cron.php

function wp_cron() {
	// Prevent infinite loops caused by lack of wp-cron.php
	if ( strpos( $_SERVER['REQUEST_URI'], '/wp-cron.php' ) !== false || ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) ) {
		return 0;
	}

	$crons = wp_get_ready_cron_jobs();
	if ( empty( $crons ) ) {
		return 0;
	}

	$gmt_time = microtime( true );
	$keys     = array_keys( $crons );
	if ( isset( $keys[0] ) && $keys[0] > $gmt_time ) {
		return 0;
	}

	$schedules = wp_get_schedules();
	$results   = array();
	foreach ( $crons as $timestamp => $cronhooks ) {
		if ( $timestamp > $gmt_time ) {
			break;
		}
		foreach ( (array) $cronhooks as $hook => $args ) {
			if ( isset( $schedules[ $hook ]['callback'] ) && ! call_user_func( $schedules[ $hook ]['callback'] ) ) {
				continue;
			}
			$results[] = spawn_cron( $gmt_time );
			break 2;
		}
	}

	if ( in_array( false, $results, true ) ) {
		return false;
	}
	return count( $results );
}

Top ↑

Changelog Changelog

Changelog
Version Description
5.1.0 Return value added to indicate success or failure.
2.1.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by 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.');
    }
    
    

You must log in before being able to contribute a note or feedback.