问题描述
我编写的php脚本,做一些后端的东西,需要运行每8小时左右。脚本需要一段时间才能执行。对于它的地狱,我尝试从我的浏览器和连接到服务器获得重置好之前的脚本终止。我的问题是 - 如果我直接运行它,ie。 php -a file.php作为cron作业,有没有任何内部时间限制执行?此脚本可能需要2-5分钟才能完成,并且无法中断。
I am coding a php script that does some back end stuff and needs to run every 8 hours or so. The script takes a while to execute. For the hell of it, I tried it from my browser and the connection to the server gets reset well before the script terminates. My question is - if I run it directly, ie. php -a file.php as a cron job, are there any internal time constraints on execution? This script may take 2-5 minutes to complete and cannot be interrupted. I've never done this before so I am not sure if php has quirks when running heavy scripts.
推荐答案
如前所述, CLI脚本默认没有时间限制。
As said before, CLI scripts by default have no time limit.
但我也想提一个替代你的cron工作方法:
你可以fork一个CLI PHP脚本从web服务器控制下的PHP脚本。我做了这么多次。如果您有一个具有较长执行时间的脚本,它必须由某些网站用户操作触发(例如构建一个非常大的归档文件,并在文件完成时通过电子邮件发送下载链接),那么这是非常有用的。
我通常使用popen()函数从一个web服务器PHP脚本分叉一个CLI脚本。这允许将参数很好地传递给新的脚本实例,如下所示:
But I would also like to mention an alternative to your cron job approach:
You can fork a CLI PHP script from a PHP script under webserver control. I have done this many times. It is especially useful if you have a script with long execution time which must be triggered by some website user action (e.g. building a very large archive file and send a download link by email when the file is complete).I usually fork a CLI script from a webserver PHP script using the popen() function. This allows to nicely transfer parameters to the new script instance like this:
$bgproc = popen('php "/my/path/my-bckgrnd-proc.php"', 'w');
if($bgproc===false){
die('Could not open bgrnd process');
}else{
// send params through stdin pipe to bgrnd process:
$p1 = serialize($param1);
$p2 = serialize($param2);
$p3 = serialize($param3);
fwrite($bgproc, $p1 . "\n" . $p2 . "\n" . $p3 . "\n");
pclose($bgproc);
}
在CLI脚本中你会收到这样的参数...
In the CLI script you would receive these params like this...
$fp = fopen('php://stdin', 'r');
$param1 = unserialize(fgets($fp));
$param2 = unserialize(fgets($fp));
$param3 = unserialize(fgets($fp));
fclose($fp);
...并执行任何与在网络服务器控制下需要很长时间。
...and do anything with them that would take to long under webserver control.
此技术在* nix和Windows环境中同样适用。
This technique works equally well in *nix and Windows environments.
这篇关于运行php脚本作为cron作业 - 超时问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!