通过Cronjob运行一个“长”的PHP脚本

时间:2013-07-03 21:46:18

标签: php cron crontab cron-task

所以我有一个需要远程服务器数据的php脚本。它是这样的:

set_time_limit(100);
ignore_user_abort(true);

$x = 0
while($x < 10){
    $data = file_get_contents("http://www.remoteserver.com/script");
    // do something with the data
}

// insert ALL the gained data in the local database

如果我在浏览器中打开脚本,则需要大约10秒钟才能完成。但是,我需要循环它不是10次,而是 24次。然后脚本大约需要22秒才能完成。我无法在循环中插入数据,我需要等到循环结束。

现在,有趣的是,当循环设置为10时,如果通过cronjob运行,脚本将设法完成。 如果设置为24,则脚本无法完成,并且未在本地数据库中插入任何数据!

这是为什么?我的问题有什么解决方案吗?我在浏览器中打开它时工作正常。

我用这个cronjob命令调用脚本:

php public_html/example.com/my_script.php

我使用此cronjob命令获得相同的结果:

curl "http://example.com/my_script.php"

2 个答案:

答案 0 :(得分:1)

在没有超时的情况下运行,set_time_limit(0)

要在不等待结果的情况下运行,请管理脚本.. php -f /path/to/file 2>&1

答案 1 :(得分:0)

我有类似的问题(并发问题)。你可能也有它,如果你的脚本需要更多的时间来执行,那么cron会调用它。尝试锁定文件,例如:

$fp = fopen(dirname(__FILE__), 'r'); 
if (flock($fp, LOCK_EX | LOCK_NB)) // lock yourself
{
    ...do your thing...
    flock($fp, LOCK_UN); // unlock yourself
}
fclose($fp);
相关问题