What is Cron and how to use it in WordPress?

Cron is a technical term used to run at fixed times or at regular intervals. Most web servers use it to maintain a server and run scheduled tasks.

The cron part of the name comes from the cron time-based work scheduling system that is available on UNIX systems.

What is WordPress Cron? How does it work?

WordPress has its own cron system for scheduling functions such as checking for updates, scheduling posts for publication, and deleting comments from the Trash. All Cron jobs are powered by WP-Cron.

WP-Cron versus Cron:

The main difference between WordPress Cron and Cron Scheduler is that wp-cron.php is only run when a user visits your website and triggers a page load. This means that WordPress requires an HTTP / HTTPS request from your website to perform scheduled tasks. The cron is queuing to run after the task.

Understanding WP-Cron Scheduling :

To simplify scheduled tasks, WordPress offers a simple method to add some default intervals and custom intervals.

The default intervals provided by WordPress are:

  • hourly
  • twicedaily
  • daily
  • weekly (since WP 5.4)

To add a custom interval, you can create a filter, such as:

add_filter( 'cron_schedules', 'example_add_cron_interval' );
function example_add_cron_interval( $schedules ) { 
    $schedules['five_seconds'] = array(
        'interval' => 5,
        'display'  => esc_html__( 'Every Five Seconds' ), );
    return $schedules;
}

This filter function creates a new interval that will allow us to run the cron task every five seconds.

Let me show you an example :

// Adds a custom cron schedule for every 5 minutes
add_filter( 'cron_schedules', 'order_time_expired_cron' );
function order_time_expired_cron( $schedules ) {
    $schedules['five_minutes'] = array(
            'interval'  => 5*60,
      'display'  => esc_html__( 'Every Minutes' ),
    );
    return $schedules;
}

if ( ! wp_next_scheduled( 'order_time_expired' ) ) {
    wp_schedule_event( time(), 'five_minutes', 'order_time_expired_cron' );
}

// Hook into that action that'll fire every five minutes
add_action( 'order_time_expired_cron', 'order_time_expired' );
if ( ! function_exists( 'order_time_expired' ) ) {
  function order_time_expired() {
    $to_email = 'test@example.com';
    	$subject  = 'Testing Cron Mail';
    	$message  = 'This mail is sent using the WordPress mail function';
    	$headers  = 'From:test@example.com';
    	wp_mail($to_email,$subject,$message,$headers); 
    }
}

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories