dongli564510 2016-09-23 10:58
浏览 230
已采纳

如何使用set_time_limit在N秒后停止php脚本?

I have that simplest possible script:

 <?php
if( ini_get('safe_mode') ){
  echo "safe mode !";
}else{
   echo "NOT safe mode !";
}

set_time_limit(3);

for ($i=0;$i<30;$i++) {
    sleep(1);
    echo $i;
}

I have as output Not safe mode 0123456....

Why does my script does not stop after 3 seconds ?

(I run it in SSH console)

  • 写回答

2条回答 默认 最新

  • doqs8936 2016-09-23 11:02
    关注

    Time spent sleeping doesn't count towards script execution time. From the manual:

    The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running. This is not true on Windows where the measured time is real.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dongmen1925 2016-09-23 11:09
    关注

    AS @iainn said in his answer, set_time_limit() only counts the actual processing time the PHP script does. So when sleeping or waiting for other processes, it won't be counted towards the limit. (Except for on Windows.)

    However, to answer the question in your title:
    In order to stop it after 3 seconds of "real time", simply create a variable that contains the starting time (in ms), and then check this inside the loop. Preferably before the sleep. Then, if it's > 3000 ms just break from the loop. ;)

    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Unity微信小游戏上调用ReadPixels()方法报错
  • ¥15 如何通过求后验分布求得样本中属于两种物种其中一种的概率?
  • ¥15 q从常量变成sin函数,怎么改写python代码?
  • ¥15 图论编程问题,有可以指导的吗
  • ¥15 DEA的CCR模型画图
  • ¥15 请假各位一个关于安卓车机的问题
  • ¥15 光谱仪怎么看这样的透射谱
  • ¥15 pyqt5 如何实现输入框输入关键词,下拉框显示模糊查询返回的结果?
  • ¥20 fluent模拟,可以燃烧和相变同时模拟吗?
  • ¥50 海康摄像头,C#如何识别车牌号码和抓取JPG