javiertoledos of Creative Science Labs
10/6/2016 - 8:59 PM

To create a cron job in wordpress for any amount of time, in this example it works for 5 mins

To create a cron job in wordpress for any amount of time, in this example it works for 5 mins

//Define our custom amounts of time
function custom_cron_schedules($schedules){
  if(!isset($schedules["5min"])){
    $schedules["5min"] = array(
      'interval' => 5*60, // time in seconds
      'display' => __('Once every 5 minutes'));
  }
  return $schedules;
}
add_filter('cron_schedules','custom_cron_schedules');

// Set our custom amount of time cron
if (! wp_next_scheduled ( 'call_cron_callback_function' )) {
    wp_schedule_event(time(),'5min', 'call_cron_callback_function');
}
add_action('call_cron_callback_function', 'cron_callback_function');

// callback function should be defined
function cron_callback_function(){
  //this place it's too quiet
}

// Default existing amounts of time
if (! wp_next_scheduled ( 'my_hourly_event' )) {
    wp_schedule_event(time(), 'hourly', 'my_hourly_event');
}
if (! wp_next_scheduled ( 'my_twicedaily_event' )) {
    wp_schedule_event(time(), 'twicedaily', 'my_twicedaily_event');
}
if (! wp_next_scheduled ( 'my_daily_event' )) {
    wp_schedule_event(time(), 'daily', 'my_daily_event');
}

// Sources: 
// - https://codex.wordpress.org/Function_Reference/wp_schedule_event
// - https://codex.wordpress.org/Plugin_API/Filter_Reference/cron_schedules