How to run PHP code only once a day?

Asked

Viewed 1,100 times

0

I’m using the Facebook and Instagram Apis on a project. I basically query posts respectively from each social network and insert in the wordpress database, saved the ID of each post and do a check before inserting to not insert duplicate posts.

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

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

3 answers

3

Simply store in a database table the date of the last search execution. When a user executes the search, you compare that date with the current one; if they are different, you execute the code that you have to execute once a day and update the last execution date; if the date is the same, you will not need to run it again.

  • 1

    Will you use a database just for this? Performance suffers from this. Saving a file would be much simpler and faster, in matters of readability and performance.

  • In fact it was just an example; in fact, you need some way to store data, be it a database or a file, be it memcached, etc.

3


As much as I already have an accepted answer, there is a much simpler way to create a connection to the database, mentioned by @Haroldo_ok. To run the code only once a day, you can save a file, which contains the next day’s timestamp. Whenever PHP is executed, timestamps are compared. If more than 1 day has passed, the code is executed again.

if (file_get_contents('ultima_verificacao') < time()) {
    file_put_contents('ultima_verificacao', strtotime('+1 day', time()));
    echo "Execute código diário aqui";
}
  • Or, if you need extreme performance gains, you can use memcached, or similar solution.

1

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

A wikipedia reference: https://pt.wikipedia.org/wiki/Crontab

  • There are advantages and disadvantages of using CRON; the advantage is that you can schedule the execution of the routine to a time when no one is using the system; the disadvantage is that the routine will be executed even if no one is going to use the routine on that particular day. Ultimately, it will depend on the need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.