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?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 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.

Solution 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

Solution 3

You can go through this link.

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

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

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

Leave a Reply