What is WP-Cron in WordPress? How is it different from a real cron job?

WP-Cron is the scheduler of WordPress. It does not run all the time like a server cron. It checks for due tasks when a page is loaded (through wp-cron.php), so a task can be late if there are no visitors.

Terminal output

$ wp cron event list –fields=hook,recurrence
hook recurrence
recovery_mode_clean_expired_keys 1 day
wp_privacy_delete_old_export_files 1 hour
wp_privacy_personal_data_cleanup_requests 1 day
wp_version_check 12 hours
wp_update_plugins 12 hours
wp_update_themes 12 hours
wp_site_health_scheduled_check 1 week

Schedule your own task with wp_schedule_event() and attach a function to its hook:

add_action( 'tc_daily_task', function () {
	update_option( 'tc_last_run', 'task ran' );
} );

if ( ! wp_next_scheduled( 'tc_daily_task' ) ) {
	wp_schedule_event( time() + 3600, 'daily', 'tc_daily_task' );
}
echo 'Scheduled: ' . ( wp_next_scheduled( 'tc_daily_task' ) ? 'yes' : 'no' ) . "\n";

do_action( 'tc_daily_task' );   // run it now, to test
echo get_option( 'tc_last_run' );
Output

Scheduled: yes
task ran

Use a real cron for big sites

Turn off the visit based trigger, and call wp-cron.php from the server every few minutes:

// wp-config.php
define( 'DISABLE_WP_CRON', true );
*/5 * * * * cd /var/www/html && wp cron event run --due-now >/dev/null 2>&1

Remember to remove the scheduled event when your plugin is deactivated, with wp_clear_scheduled_hook().


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
What is the WordPress default feed cache recreation time? How to change it?
How to increase maximum execution time in PHP and WordPress?
What are transients in WordPress?
What is WP-Cron in WordPress? How is it different from a real cron job?
How to speed up a WordPress site?