0

So i have written a program to call API from a website each 20 minutes. i"ve done this by giving the sleep() function in php. i have given this delay inside a while loop. how can i execute the same function using cron? this is the while loop..

<?php
@ini_set("output_buffering", "Off");
@ini_set('implicit_flush', 1200);
@ini_set('zlib.output_compression', 0);
@ini_set('max_execution_time',0);
//code;
while($r=mysql_fetch_array($res))
 {

    //code;
    if(sleep(1200)!=0)
    {
        echo "sleep failed script terminating"; 
        break;
    }
    flush();
    ob_flush();
}
?>
alex_gabriel
  • 373
  • 1
  • 8
  • 20
  • 1
    Use crontab. `*/20 * * * * php -f path/to/script.php` – ʰᵈˑ Oct 13 '14 at 08:20
  • Your question title doesn't really match the question body... Are you asking **how** you should do this or **whether** you should do this? – Lix Oct 13 '14 at 08:21
  • @hd:Can i call a crontab inside that while loop..? instead of the sleep() function? – alex_gabriel Oct 13 '14 at 08:22
  • No. You need to use `crontab -e` and set it up. Remove all the `sleep()` logic within your script. – ʰᵈˑ Oct 13 '14 at 08:23
  • @lix:I'm asking whether we should use cron instead of sleep(). – alex_gabriel Oct 13 '14 at 08:26
  • @hd: ok..so if we are using crontab -e ,is the while loop being executed each 20 mins or the whole php file? – alex_gabriel Oct 13 '14 at 08:29
  • The whole file will be called every 20 minutes, executed by the cron. – ʰᵈˑ Oct 13 '14 at 08:30
  • is there any way that you suggest to execute the while loop only., after each 20 minutes..? – alex_gabriel Oct 13 '14 at 08:31
  • Better software design? What's needed to run the loop? You could pass an argument into the script and skip everything up to the loop if the argument is supplied. – ʰᵈˑ Oct 13 '14 at 08:33
  • @hd:i am doing a people search API in our script.So we are calling the API based on the entries that we already have in our database.We need to execute a delay for each entry to get the API response. – alex_gabriel Oct 13 '14 at 08:42

1 Answers1

3

Ditch the sleep, and use the cron.

  • In your console type crontab -e
  • Set up the following;

*/20 * * * * php -f path/to/script.php
Community
  • 1
  • 1
ʰᵈˑ
  • 11,279
  • 3
  • 26
  • 49