Cron Job WordPress.

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.

add_filter( ‘cron_schedules’, ‘CustomCronScheduler’ );
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;
}

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') ;
}


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

Enjoy

Leave a Comment

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

Scroll to Top