我有一个运行时间为34秒的PHP脚本。但它在30秒后就死了。我猜我的网站管理员有30秒的时间限制.
我正在考虑将脚本分成两部分,即PHP-1和PHP-2。
我可以从PHP-1调用PHP-2并杀死PHP-1吗?这两个脚本都必须按顺序运行,因此不可能使用cron调用这两个脚本。我的主机提供cron,间隔5分钟,不允许更改开始时间
-Will这绕过了主机设置的时间限制吗?
发布于 2010-03-22 14:56:50
您应该使用set_time_limit()函数,它在大多数情况下都很有用。
或者,在Linux/Unix上,您可以尝试将脚本作为后台进程运行。PHP CLI可用于此目的,通过CLI运行的脚本没有时间限制。您可以使用exec/system或类似的PHP函数来启动PHP CLI,让它在后台运行PHP脚本,立即将控制权返回给脚本。在大多数情况下,通过CLI运行的PHP脚本的行为与它在CGI环境中的行为一样,但与环境相关的差异很少,例如没有时间限制。
这里有一种方法:
exec("/usr/bin/php script.php > /dev/null &");
^ ^ ^ ^
| | | |
| | | +-- run the specified process in background
| | +-------------- redirect script output to nothing
| +------------------------- your time consuming script
+-------------------------------------- path to PHP CLI (not PHP CGI)更多详情请访问:Running a Background Process in PHP
发布于 2010-03-22 14:36:43
看看set_time_limit()吧。
发布于 2010-03-22 15:18:40
作为CLI运行它将自动消除时间限制。您可以使用cron,正如Salman A所描述的那样。我有一个每30分钟运行一次的脚本。它是这样的:
<?php
$timeLimit = 1740; //29 mins
$startTime = time();
do
{
$dhandle = opendir("/some/dir/to/process");
while ( (false !== ($file = readdir($dhandle))) ) {
//do process.
}
sleep(30);
} while (!IsShouldStop($startTime, $timeLimit));
function IsShouldStop($startTime, $timeLimit)
{
$now = time();
$min = intval(date("i"));
if ( ($now > $startTime + $timeLimit) && ($min >= 29 || $min >= 59) )
{
echo "STOPPING...<br />\n";
return true;
}
else
{
return false;
}
}
?>我为什么要这么做?因为我在某处读到过PHP在垃圾回收方面做得很差。所以我每30分钟就杀掉它一次。它不是那么健壮。但是,考虑到共享主机的限制。这是我最好的方法。您可以将其用作模板。
https://stackoverflow.com/questions/2490373
复制相似问题