如何让PHP脚本永远与Cron Job一起运行?

前端之家收集整理的这篇文章主要介绍了如何让PHP脚本永远与Cron Job一起运行?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. <?PHP
  2. while(true){
  3. //code goes here.....
  4. }
  5. ?>

我想制作一个PHP Web服务器,那么如何使用Curl使这个脚本永远运行?

不要忘记将最大执行时间设置为无限(0).

如果这是你的意图,那么最好确保你不要运行多个实例:

  1. ignore_user_abort(true);//if caller closes the connection (if initiating with cURL from another PHP,this allows you to end the calling PHP script without ending this one)
  2. set_time_limit(0);
  3.  
  4. $hLock=fopen(__FILE__.".lock","w+");
  5. if(!flock($hLock,LOCK_EX | LOCK_NB))
  6. die("Already running. Exiting...");
  7.  
  8. while(true)
  9. {
  10.  
  11. //avoid cpu exhaustion,adjust as necessary
  12. usleep(2000);//0.002 seconds
  13. }
  14.  
  15. flock($hLock,LOCK_UN);
  16. fclose($hLock);
  17. unlink(__FILE__.".lock");

如果在CLI模式下,只需运行该文件.

如果在Web服务器上的另一个PHP中,您可以启动必须像这样运行的那个(而不是使用cURL,这消除了依赖):

  1. $cx=stream_context_create(
  2. array(
  3. "http"=>array(
  4. "timeout" => 1,//at least PHP 5.2.1
  5. "ignore_errors" => true
  6. )
  7. )
  8. );
  9. @file_get_contents("http://localhost/infinite_loop.PHP",false,$cx);

或者你可以使用wget从linux cron开始,如下所示:

  1. `* * * * * wget -O - http://localhost/infinite_loop.PHP`

或者您可以使用bitsadmin运行.bat文件从Windows Scheduler启动,该文件包含以下内容

  1. bitsadmin /create infiniteloop
  2. bitsadmin /addfile infiniteloop http://localhost/infinite_loop.PHP
  3. bitsadmin /resume infiniteloop

猜你在找的PHP相关文章