wp_doing_cron()WP 4.8.0

Determines whether the current request is a request to Cron. Conditional tag.

This is a wrapper to check if the constant DOING_CRON is set:

if( defined( 'DOING_CRON' ) && DOING_CRON ){
	// cron task
}

The constant DOING_CRON is set only when the request was initiated from the file wp-cron.php. That is, for this conditional function to work, WP needs to be loaded through the file wp-cron.php. Usually, this loading is initiated by the Cron execution through the function wp_cron(). All of this WordPress does automatically!

There is exactly the same wrapper to check AJAX requests: wp_doing_ajax()

1 time — 0.000021 sec (very fast) | 50000 times — 0.12 sec (very fast) | PHP 7.1.2, WP 4.8
Hooks from the function

Returns

true|false.

  • true - if this is a cron request.
  • false - if this is any other request except Cron.

Usage

if( wp_doing_cron() ){
	// WP loaded through cron
}

Examples

0

#1 Do anything when a cron request is in progress only.

For example, let's remove my_schedule_hook event from the schedule cron, when the next cron request is triggered.

add_action( 'shutdown', function(){

	if( wp_doing_cron() ){

		// delete cron task
		$timestamp = wp_next_scheduled( 'my_schedule_hook' );

		wp_unschedule_event( $timestamp, 'my_schedule_hook' );
	}
} );

Changelog

Since 4.8.0 Introduced.

wp_doing_cron() code WP 7.0

function wp_doing_cron() {
	/**
	 * Filters whether the current request is a WordPress cron request.
	 *
	 * @since 4.8.0
	 *
	 * @param bool $wp_doing_cron Whether the current request is a WordPress cron request.
	 */
	return apply_filters( 'wp_doing_cron', defined( 'DOING_CRON' ) && DOING_CRON );
}