How To Execute Wp_Schedule_Event Event On Custom Time Interval In WordPress

Here we learn about how to execute the Wp_Schedule_Event event on custom time interval in WordPress.

Custom code copied and paste into your child theme’s functions.php file.

Syntax:

<?php wp_schedule_event( int $timestamp, string $recurrence, string $hook, array $args = array() ) ?>

The following list of Parameters:

  • $timestamp(int)(Required) – Pass timestamp (UTC) for next run the event.
  • $recurrence(string)(Required) – Pass the event should subsequently.
  • $hook(string)(Required) – Pass the action hook to execute.
  • $args(array)(Optional) – Pass the each separate argument to the hook’s callback function.

Example:

<?php
function add_every_two_minutes( $schedules ) {
  $schedules['every_two_minutes'] = array(
    'interval'  => 120,
    'display'   => __( 'Every 2 Minutes', 'textdomain' )
  );	 
  return $schedules;
}
add_filter( 'cron_schedules', 'add_every_two_minutes' );

//Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'bl_cron_hook' ) ) {
  wp_schedule_event( time(), 'every_two_minutes', 'bl_cron_hook' );
}
///Hook into that action that fire every two minutes
add_action( 'bl_cron_hook', 'cron_function_for_execute' );

//create your function, that runs on cron
function cron_function_for_execute(){
  //your function...		
}
?>

Submit a Comment

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

Subscribe

Select Categories