简体   繁体   中英

execute php function every 20 seconds

I have a PHP script to parse live scores from JSON url,then check if some scores are change it call another php script to push notifications to IOS devices.

my question is how can i make the first script run every 20 seconds.

It depends on the host OS that you're using. For linux/unix/etc. the preferred tool for scheduling tasks is cron . For Windows or Mac or anything like that there are other built-in schedulers.

Using cron, to schedule a task to run every minute might look something like this:

* * * * * /path/to/command

The granularity, however, seems to only go to the minute. So without a more granular task scheduler, you may need to internally handle the 20 second delay.

One idea could be to wrap the task in a script which runs the command, sleeps for 20 seconds, runs the command again, sleeps for 20 seconds, and runs the command again. Then the cron job would call that wrapping script. My bash is a little rusty, but the idea would look something like this:

/path/to/command
sleep 20
/path/to/command
sleep 20
/path/to/command
$total_time = 0;
$start_time = microtime(true);
while($total_time < 60)//run while less than a minute
  {
    //DoSomething;
    echo $total_time."\n";
    sleep(20);//wait amount in seconds
  $total_time =  microtime(true) - $start_time ;
  } 

add this to cronjob to run every minute.

maybe you can try sleep

while(1) {
    exec('php path/to/script.php');
    sleep(20);
}

Generaly a cronjob is perfect for this kind of task. Have a look at this here: http://www.thegeekstuff.com/2011/07/php-cron-job/
If that's not applicable you might be able to Script something for the PHP CLI http://php.net/manual/en/features.commandline.php which allows you unlimited runtime. Just put a while(true) loop with a sleep() in there and run it with the php command like > php yourscript.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM