PHP timer

Asked

Viewed 2,033 times

3

I need to implement a feature, in which a certain code is executed several times after a time interval.

For example, read files provided by the API every 20 minutes. I tried something like that, but I haven’t tried it yet, I just wish I had an easy and sure way to do it.

   while(true)
   {
      // Executa o codigo aqui;
      usleep(1200);

   }

Does PHP have any method for scheduling tasks? What would be the mechanism to cancel the loop, if the above idea is valid?

  • Francisco, I don’t know enough php to answer all your questions, but I can tell you that you can use break; to get out of your loop.

  • The usleep / Sleep function serves to delay the execution of a script and it is not recommended to put very high values, because the script will continue running until the time runs out, that is, it will continue consuming memory throughout the running time. To schedule tasks, you must use the system tools, be it Linux or Windows, both have resources for this. In the case of Linux, the feature is called cron job, in Windows it is task manager, if I’m not mistaken. Both tools will run your PHP script as scheduled, eliminating the use of Sleep. Use Sleep

  • only in very specific cases, such as when you want to make a late in a loop that sends emails to avoid flooding the system with a very fast execution.

  • I think it’s the same problem with that question: Search database table information with PHP every 10 minutes - The answers are independent of the task that will be executed

1 answer

2

Cron job is the right way to do it ;)

Calls an index.php every minute:

1 * * * * wget www.meusite.pt/crons/index.php

Then inside that php file just do a "ifs":

ore_user_abort();
set_time_limit(3600);

// a cada hora
if(date('i')==59){
    $this->hour();
}

// a cada minuto
$this->minute();

Something out there... Some doubt warns ;)

Hug and good projects!

Browser other questions tagged

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