Schedules for WordPress Cron add

In WordPress we have a filter cron_schedules which allow us to add custom schedule.

We have see we can use the function wp_get_schedules() to see all the existing schedules.

In above example we have below schedules:

To add our own unique schedules, we may utilize the cron_schedules. Let’s add an action to the every_ten_minutes schedule.

<?php
/**
* Add Cron Schedules
*
* @todo Change the `prefix_` and with your own unique prefix.
*
* @since 1.0.0
*
* @param array() $schedules Existing schedules.
* @return array
*/
if( ! function_exists( 'prefix_add_cron_schedules' ) ) :
function prefix_add_cron_schedules( $schedules = array() ) {
$schedules['every_ten_minutes'] = array(
'interval' => 600, // 600 seconds means 10 minutes.
'display' => __( 'Every 10 minutes', 'textdomain' ),
);
return $schedules;
}
add_filter( 'cron_schedules', 'prefix_add_cron_schedules' );
endif;

We have implemented a new schedule with a 600 second interval, which implies every 10 minutes.

Create a WordPress Cron Event

Every_ten_minutes is the custom schedule that we have registered.

Let’s now add a cron event or a custom schedule event.

The wp_schedule_event() method allows us to register the schedule event.

Check out the code below:

<?php
/**
* Add schedule event or Cron event with wp_schedule_event()
*
* @todo Change the `prefix_` and with your own unique prefix.
*
* @since 1.0.0
*
* @return void
*/
if( ! function_exists( 'prefix_add_scheduled_event' ) ) :
function prefix_add_scheduled_event() {
// Schedule the event if it is not scheduled.
if ( ! wp_next_scheduled( 'prefix_cron_hook' ) ) {
wp_schedule_event( time(), 'every_ten_minutes', 'prefix_cron_hook' );
}
}
add_action( 'admin_init', 'prefix_add_scheduled_event' );
endif;

The prefix_cron_hook scheduling event is registered here. Every 10 minutes, this planned event is set to trigger.

However, we must add a step that is identical to our planned event.

The same action, prefix_cron_hook, can be used to carry out several tasks. Let’s add a example job now.

Create a WordPress Cron Job

To execute our scheduled event with hook prefix_cron_hook, we may utilize the method add_action().

For reference, see the code below:

<?php
/**
* Task to perform
*
* @todo Change the `prefix_` and with your own unique prefix.
*
* @since 1.0.0
*
* @return void
*/
if( ! function_exists( 'prefix_cron_task' ) ) :
function prefix_cron_task() {
$to = 'sendto@example.com';
$subject = 'This Email is generated using WordPress cron job.';
$body = 'The email body content. Hire Prakash Tyata if you need further assistance.';
$headers = array('Content-Type: text/html; charset=UTF-8');

wp_mail( $to, $subject, $body, $headers );
}
add_action( 'prefix_cron_hook', 'prefix_cron_task' );
endif;

Categorized in: