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?

Related posts

3 comments

  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.

  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

Comments are closed.