Cron Job WordPress (WP-Cron)

What Is WordPress Cron Job?

WordPress Cron Job is how WordPress handles scheduling time-based tasks in WordPress.“Cron” Means the cron time-based task scheduling system which is available on UNIX systems.

A WordPress CRON job is a task or action which is scheduled to run automatically at specific intervals. To simplify scheduling tasks, WordPress Cron Scheduling three default intervals and very easy method for adding custom intervals.
The default intervals provided by WordPress are:

  • hourly
  • twicedaily
  • daily

For adding a custom interval, you can use filter.
Example custom cron schedule for every 10 Seconds & 10 days.


function CustomCronScheduler( $schedules ) {
  if(!isset($schedules['10sec'])){
    $schedules['10sec'] = array(
      'display' => __( 'Every 10 Seconds'),
      'interval' => 10,
    );
  }
  if(!isset($schedules['after10days'])){
    $schedules['after10days'] = array(
      'display' => __( 'Once in 10 days'),
      'interval' => 10*DAY_IN_SECONDS,
    );
  }
  return $schedules;
}
add_filter(‘cron_schedules’,‘CustomCronScheduler’ );
wp_schedule_event( int $timestamp, string $recurrence, string $hook, array $args = array() );

wp_schedule_event function Schedules a hook which will be triggered by WordPress at the specified interval. The action will trigger when someone visits your WordPress site if the scheduled time has passed.


if (!wp_next_scheduled('TenDaysCronHook')) {
  wp_schedule_event (time (), "after10days", 'TenDaysCronHook') ;
}
if (!wp_next_scheduled ('TensecCronHook')) {
  wp_schedule_event (time (), "10sec", 'TensecCronHook') ;
}

function TenDaysCronFunction (){
  //action u want to perform in every 10 days.
}
add_action ('TenDaysCronHook','TenDaysCronFunction') ;

function TensecCronFunction (){
  //action u want to perform in every 10 sec.
}
add_action ('TensecCronHook','TensecCronFunction') ;

Enjoy

Leave a Comment

Your email address will not be published.

Scroll to Top

Let's Connect With EoxysIT Team