我购买了一个共享主机,他们为php文件的执行设置了30s的限制。我的脚本使用 CRON 运行,其执行时间可能需要 30 秒以上。
基本上在我的脚本中有一个 foreach 循环,可以将条目添加到数据库中。
foreach( $items as $item ) {
// prepare pdo query etc.
$db->execute();
}
有没有办法以某种方式省略限制?就像在 20 秒后暂停循环然后重新运行或 sth 一样?
顺便说一句,我不能使用set_time_limit()
。
CRON 作业每天仅运行一次。
您可以做的是检查脚本在每次迭代中的运行时间,并在接近最大执行时间时保存已处理的最后一条记录。然后在下一次运行时赶上并从该特定记录开始。它应该像这样工作:
// place this at the very start of your script.
$start_time = microtime(true); // true is important, otherwise it'll return a string.
$max_execution_time = ini_get('max_execution_time');
// logic to retrieve the records, take the last processed record into account
// so in your query do something like WHERE id > last_record_processed
foreach( $items as $item ) {
// do something interesting with the item
$current_time = microtime(true);
if( ( $current_time - $start_time) > ( $max_execution_time - 5) ) {
$last_record_processed = $item;
// store the id or whatever somewhere;
break;
}
}
您必须自己弄清楚存储最后处理的记录的最佳方法是什么,要建立什么安全裕度(现在:5秒)等。
为了做到这一点,你将每小时运行一次cron,甚至可能更规律。否则,它将每天处理您的部分记录。但是,您应该首先检查它是否正在继续当前批次,或者必须重新开始(只有在一天过去后才应该发生)。
在你的 php 脚本中,添加这一行
ini_set ('max _ execution_time', -1);
当然,它仅在您的托管服务器允许的情况下才有效。