How to run PHP code only once a day?

0

I'm using the facebook and instagram APIs in a project. I basically do the query of posts respectively of each social network and I insert in the database of wordpress, I saved the ID of each post and I do a check before entering not to insert duplicate posts.

But whenever I load the site, it takes time to load because it searches for posts on facebook and instagram, which is damaging the performance of the site.

What I want to do is that this search for new posts in instagram and facebook be done only once a day. If a user enters the site and performs the search, the next users will no longer perform this search. And then the next day the first user performs the search and the others do not and so on.

    
asked by anonymous 26.10.2016 / 18:33

3 answers

3

Although you already have an accepted answer, there is a much simpler way to create a connection to the database mentioned by @Haroldo_OK. To execute the code only once a day, a file containing the next-day timestamp can be saved. Whenever PHP is run, the timestamps are compared. If more than 1 day has passed, the code runs again.

if (file_get_contents('ultima_verificacao') < time()) {
    file_put_contents('ultima_verificacao', strtotime('+1 day', time()));
    echo "Execute código diário aqui";
}
    
26.10.2016 / 18:56
3

Simply save the date of the last run of the search to a database table. When a user performs the search, you compare that date with the current one; if they are different, you run the code that has to run once a day and updates the date of the last run; if the date is the same, it will not be necessary to run again.

    
26.10.2016 / 18:38
1

Another way to get the same result is to use a task scheduler (in Linux it's called CRON) so that the load execution is performed automatically by the Operating System, preferably out of peak hours, without compromising / competing with the accesses to your app.

A reference from wikipedia: link

    
26.10.2016 / 18:45