如果我们在程序中使用延迟,我们应该使用cron吗.


should we use cron if we are using delay in our program...?

所以我编写了一个程序,每20分钟从一个网站调用API。我通过在php中提供sleep()函数来实现这一点。我在while循环中给出了这个延迟。如何使用cron执行相同的函数?这是while循环。。

<?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();
}
?>

放弃sleep,使用cron。

  • 在控制台中键入crontab -e
  • 设置以下内容

*/20 * * * * php -f path/to/script.php
  • 在CentOS上安装crontab
  • Windows计划任务
  • 在Linux或UNIX下向cron添加作业