function js_cron_exec() { // Scheduled task code here } add_action( 'js_cron_hook', 'js_cron_exec' ); // Schedule the task if not already scheduled if ( ! wp_next_scheduled( 'js_cron_hook' ) ) { wp_schedule_event( time(), 'daily', 'js_cron_hook' ); } // Remove the scheduled task // $timestamp = wp_next_scheduled( 'js_cron_hook' ); // wp_unschedule_event( $timestamp, 'js_cron_hook' );
Few things to mention about the code:
- add_action() will create your hook.
- The first parameter of add_action() is the name of the hook you are creating. Name it as you please and use a name prefix. The scheduled event will call this.
- The second parameter of add_action() is the name of the function to call. Again, name it whatever. Use a name prefix. The hook will call this.
- wp_schedule_event() will schedule the event. The second parameter can accept: ‘hourly’, ‘twicedaily’, ‘daily’, ‘weekly’.
WP-Cron is how WordPress handles scheduling time-based tasks in WordPress, such as checking for updates and publishing scheduled posts.
With WP-Cron, all scheduled tasks are put into a queue. On each page load, it works by checking a list of scheduled tasks to see what needs to be run. Any tasks that need to be run are then executed.
So while you canโt be 100% sure when your task will run, you can be 100% sure that it will run eventually. Put another way, if your task is scheduled to run at 2:00PM but your next page load is not until 5:00PM, the task with run at 5:00PM.