Is is possible to start the WP-Cron randomly between 30 and 60 minutes?
What i have
add_action('my_hourly_event', 'do_this_hourly');
function my_activation()
{
if(!wp_next_scheduled( 'my_hourly_event' ))
{
wp_schedule_event( current_time( 'timestamp' ), 'hourly', 'my_hourly_event');
}
}
add_action('wp', 'my_activation');
function do_this_hourly()
{
// do something
}
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:
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 plugin If 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 event
register_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 event
add_action( 'my_awesome_event', 'do_this_in_awesome_event' );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With