is your wp-cron date late again?

wpHakka.com.br - underground guerrilla - plugin arsenal for wp warfare

stop keeping her on ice …

here is how to teach wp to be on-the-hour, it also turns the game around, no complicate filter adding, hook adding and interval calculating anymore

what do you need:
– run_it() a function to be executed
– $the_hour is the day time you want it to run, like 08:00, 20:30
– $active an option as activation switch, like 0 or 1

that’s all, you could create a wp option to store your script settings and retrieve $the_hour and $active from it, that avoids hardcoding the values and makes it possible un- and re-schedule the event instantly easily from the adm form

here the php block to add to your script:

if ($active && $the_hour && !wp_next_scheduled(‘by_on_the_hour’)) {
     $next_date = strtotime(‘tomorrow ‘ . $the_hour);
     wp_schedule_single_event( $next_date, ‘be_on_the_hour’ );
}
add_action(‘be_on_the_hour’, ‘run_it’);


that’s all, here is what it does: “tomorrow” is used to make sure you do not hit a past time on first schedule, that is what most people miss when scheduling in wp and all get’s messy

instead of scheduling a recurring event, we schedule just one and soon it is due, it is rescheduled for the next date, that is what the IF statement does, does the event exist? it does nothing, isn’t it scheduled and it is rescheduled

first it checks if both vars are true, they are authoritative for execution, means if any of them isn’t set in wp options or is hardcoded to 0 the event isn’t scheduled, that’s the whole control you need

the add_action hook then activates it and runs run_it() on time

be aware that $the_hour is UTC time, so set it right to run at the correct local time, if you are at UTC-3 then set it to 09:00 in order to run it at 06:00 your local time

so, that was a short lesson for easyfication of a typical wp problem, often called a nighmare because wp cron really is

use it and don’t make her mad any more :)


hakka quote … most people have a skull, I have a light bulb powered by a crap burner oven

Comments

Leave a Reply

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

Author name should not pass 30 characters.

Author name should have only letters and spaces.