Reset Transient on New Day

I have a plugin that interfaces with an API and am storing retrieved schedule data in a transient.

Storing the transient for 24 hours:

set_transient($schedule_cache, $schedule_data, 60 * 60 * 24);

The problem (I think) is: Which 24 hours is it being stored for? I want TODAY to be displayed, but if the transient was set at 11PM last night when someone loaded the page, we’re going to be displaying YESTERDAY until 11PM TONIGHT.

The inelegant approach I’m working with is to store a second transient with a unique TODAY identifier:

$this::$time_tracker = date('Fd', strtotime("today")); # 'March30' 
set_transient($schedule_timer, $this::$time_tracker, 60 * 60 * 48);

And then if the current time tracker doesn’t match transient, delete all of the transients (there are others for pagination):

if($last_look != $this::$time_tracker)
    // Delete all the transients and save new ones

Minimal working example:

class transientIssues {

    public function __construct(){
        $this::$time_tracker = date('Fd', strtotime("today"));
    }

        $schedule_cache="sched_che";
        $schedule_timer="sched_tim";

        $last_look = get_transient($schedule_timer);

        if ( $last_look != $this::$time_tracker ){
            // delete_transient( $schedule_cache );
            // Replaced above with the following so we could deal with multiple date ranges being called.
            global $wpdb;
            $wpdb->query( "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE ('%sched_ch%' OR '%sched_tim%')" );
        }

        if ( false === get_transient( $schedule_cache ) ) {

            $api = $this->instantiate_API();
            if ($api == 'NO_SOAP_SERVICE') {
                pr($api);
                }else{
                $api->gettData(); 
                }

            set_transient($schedule_timer, $this::$time_tracker, 60 * 60 * 24);
            set_transient($schedule_cache, $schedule_data, 60 * 60 * 24);

             // END caching*/
        }
}

Does this seem like a reasonable approach? I would welcome insights.

1 Answer
1

There is no reliable way to achieve what you want with the Transients API – or even, if you have been considering it, with the WP Cron system. The problem is in a nutshell: Those API systems depend on user input. If you want to know more about it, do a research, as this has been discussed a couple of times.
To have a reliable solution, you can use the real – the WP one has pretty much nothing to do with it and in my mind it shouldn’t even be called alike, but whatever – CRON system and the cronjobs you can set up with it. I’m not going into depth here, because you will find enough starting information about »How the real CRON can be used with WordPress« on the internet. As @MarkKaplun rightfully pointed out, WP CRON and real CRON can be used in conjunction to achieve your goal.

Leave a Comment