Wordpress wp_schedule_event randomly between 30 and 60 minutes Wordpress wp_schedule_event randomly between 30 and 60 minutes wordpress wordpress

Wordpress wp_schedule_event randomly between 30 and 60 minutes


Unfortunately the wp_schedule_event doesn't have 30 min and accepts only these intervals: hourly, twicedaily(12H), daily(24H).

In my opinion is a bit strange to have a scheduled event that can change randomly, and probably you should look at a different implementation.Without discussing your choice I am going to provide a possible answer.

There are plugins with hooks into the Wordpress cron system to allow different time interval.

One solution is to set only one cron every 30 minutes and have a custom function that randomly will be executed or not.

if (rand(0,1)) { ....

For example:

  1. after 30 min the function will be executed (and you have 30 min cron)
  2. after another 30 min the function simply skip the run
  3. for the next 30min will be triggered again and executed(and you have your 1 hour cron).

The problem there is to force the execution at 1 hour (after 1 skip), because you can end up to skip more than +30min. This can be achieved storing the value of the last execution.

Another solution is to have 2 cron (30 min and 1 hour) nearly in the same time and having a custom function that will trigger the 30 min if the 1 hour is not running and so on.

Here is a nice Wordpress cronjob pluginIf you need to store the cron execution safely in a Wordpress table you can use the Wordpress add_option function, with get_option and update_option to get and update its value.


In the code below, I'll be using activation hook instead of wp hook, feel free to use after_switch_theme if it's a theme your code resides in...

You can use wp_schedule_single_event() and simply add a single event to happen randomly between 30-60 minutes every time the event happens ;)

/** * Registers single event to occur randomly in 30 to 60 minutes * @action activation_hook * @action my_awesome_event */function register_event() {    $secs30to60min = rand( 1800, 3600 ); // Getting random number of seconds between 30 minutes and an hour    wp_schedule_single_event( time() + $secs30to60min, 'my_awesome_event' );}// Register activation hook to add the eventregister_activation_hook( __FILE__, 'register_event' );// In our awesome event we add a event to occcur randomly in 30-60 minutes again ;)add_action( 'my_awesome_event', 'register_event' );/** * Does the stuff that needs to be done * @action my_awesome_event */function do_this_in_awesome_event() {    // do something}// Doing stuff in awesome eventadd_action( 'my_awesome_event', 'do_this_in_awesome_event' );