JBoss
JBoss

Reputation: 776

wp_schedule_event and Daylight Savings

So I ran into an issue on a website this morning that uses WP Cron. The code looks like this:

//Schedule the cron to run if not scheduled
if ( ! wp_next_scheduled( 'my_check_cron_event' ) ) {
    wp_schedule_event( strtotime('tomorrow America/New_York') , 'daily', 'my_check_cron_event' );
}

The issue is pretty simple. That code works fine, essentially I want to run the function at midnight local time, every day. So when I first run the function - it gets the timestamp for midnight tomorrow - local time. And ever since - the functino has been running.

Now this weekend - because of daylight savings time, the function doesn't actually ever get RESCHEDULED - its just set to run every 24 hours. So the function started running at 11pm. Of course that's easy to fix - but will just break again. I can't really find any good posts on the topic - how would you deal with:

wp_schedule_event running daily when daylight savings time changes?

Just to preempt an obvious answers here: I can't run a proper cron - it needs to be done through wp. Our host simply doesn't support it, it sucks - but that's the client. Any advice would be greatly appreciated!

Upvotes: 4

Views: 1169

Answers (1)

JBoss
JBoss

Reputation: 776

So for anyone coming across this, I had to come back to this for a permanent solution today - as Daylight savings is about to change! The root issue here is that wp_schedule_event - accepts a parameter thats a number of seconds until the next run. That parameter is saved to the cron array - and it really doesn't care what timezone you're in. It just keeps running at that interval. In order to fix this - I had to switch to wp_schedule_single_event.

It seems counter-intuitive, because we want this to run on an interval. But the difference is - we NEED to recalculate the next timestamp to run at:

if ( ! wp_next_scheduled( 'my_check_cron_event' ) ) {
   wp_schedule_single_event( strtotime('tomorrow America/New_York'), 'my_check_cron_event' );
}

The difference here is strtotime() will get the correct timestamp each DAY - accounting for daylight savings, rather than simply running every 24 hours. Hope that helps someone!

Upvotes: 4

Related Questions