Run function at specific time

I have a WordPress function that I want to run once daily at a specific time. How should I go about doing this, since WP cron cannot be set to a particular time?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

you can absolutely use wp_cron to specify a time:

add_action( 'my_scheduled_event', 'prefix_my_scheduled_event' );
/**
 * On the scheduled action hook, run a function.
 */
function prefix_my_scheduled_event() {
    // do something 
}
//going to use the strtotime function, so a good habit to get into is to set the PHP timezone to UTC
default_timezone_set( 'UTC' );
//define a timestamp to run this the first time.  4:20 is as good a time as any.
$timestamp = strtotime( '2013-12-14 16:20:00' ); 
//set a recurrence interval - WP has three default intervals: hourly, daily & twicedaily
$recurrence = 'daily';
//define the hook to run
$hook = 'my_scheduled_event'
//you can pass arguments to the hooked function if need be.  this parameter is optional:
$args = null;
//the following will run your function starting at the time defined by timestamp and recurring every $recurrence
wp_schedule_event( $timestamp, $recurrence, $hook, $args );

This is an over simplified example. Some type of checking needs to be done so that you don’t end up with a boatload of hooks scheduled, but it should give you an idea of how to set it up for a particular time. Further, it needs to be understood that wp_cron is triggered by page loads so if your site hasn’t got huge amounts of traffic, then the function won’t fire precisely at the time defined. There are workarounds for this though.

Method 2

Just to add to @Will the Web Mechanic’s answer.
I needed to use

date_default_timezone_set()

default_timezone_set didn’t work for me

Method 3

You can go through this link.

http://codex.wordpress.org/Function_Reference/wp_schedule_event


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x