How to run a function every 5 minutes?

You can create new schedule times via cron_schedules:

function my_cron_schedules($schedules){
    if(!isset($schedules["5min"])){
        $schedules["5min"] = array(
            'interval' => 5*60,
            'display' => __('Once every 5 minutes'));
    }
    if(!isset($schedules["30min"])){
        $schedules["30min"] = array(
            'interval' => 30*60,
            'display' => __('Once every 30 minutes'));
    }
    return $schedules;
}
add_filter('cron_schedules','my_cron_schedules');

Now you can schedule your function:

wp_schedule_event(time(), '5min', 'my_schedule_hook', $args);

To only schedule it once, wrap it in a function and check before running it:

$args = array(false);
function schedule_my_cron(){
    wp_schedule_event(time(), '5min', 'my_schedule_hook', $args);
}
if(!wp_next_scheduled('my_schedule_hook',$args)){
    add_action('init', 'schedule_my_cron');
}

Note the $args parameter! Not specifying the $args parameter in wp_next_scheduled, but having $args for wp_schedule_event, will cause an almost infinite number of the same event to be scheduled (instead of just one).

Finally, create the actual function that you would like to run:

function my_schedule_hook(){
    // codes go here
}

I think it is important to mention that wp-cron is checking the schedule and running due scheduled jobs each time a page is loaded.

So, if you have a low traffic website that only has 1 visitor an hour, wp-cron will only run when that visitor browses your site (once an hour). If your have a high traffic site with visitors requesting a page every second, wp-cron will be triggered every second causing extra load on the server.

The solution is to deactivate wp-cron and trigger it via a real cron job in the time interval of you fastest repeating scheduled wp-cron job (5 min in your case).

Lucas Rolff explains the problem and gives the solution in detail.

As an alternative, you could use a free 3rd party service like UptimeRobot to query your site (and trigger wp-cron) every 5 minutes, if you do not want to deactivate wp-cron and trigger it via a real cron job.

Leave a Comment