每5分钟在服务器上执行一次php脚本

时间:2016-02-10 16:09:39

标签: php mysql cron

我想每5分钟运行一个php脚本,处理一些简单的mysql查询以识别潜在的错误,如果错误被记录为数据库条目,php脚本会发送一封电子邮件。

从我的研究来看,似乎cron作业(或任务调度程序)通常会在指定的时间处理脚本,但是我无法在我正在使用的托管服务中找到此选项(谁运行" Parallels Plesk Panel 11.0.9"作为我可以访问的管理界面。)

因此我尝试了以下"技巧":

<?php
$active = $_GET["a"];
set_time_limit(0);
while($active == 1){
    include 'alert_exe.php';
    sleep(300); // execute script every 5 mins
}
?>

要激活脚本,我输入网址(&#34; ... / alert.php?a = 1&#34;)。这可以在几分钟内正常工作,但是在2或3分钟之后,脚本会停止执行。

任何想法如何阻止脚本停止或替代建议如何每5分钟实现脚本的自动执行(无法访问cron作业)?

谢谢!

3 个答案:

答案 0 :(得分:5)

托管服务可以保护其服务器不会因长时间运行的脚本而过载,并且会配置超时,此类脚本将被中止(请参阅PHP: Runtime Configuration Settings max_execution_time 特别是)。

如果您的PC可以保持打开状态,另一种解决方案是让它每5分钟向服务器发送一次请求:

<?php
    // Your PHP code that has to be executed every 5 minutes comes here
?>
<script>
setTimeout(function () { window.location.reload(); }, 5*60*1000);
// just show current time stamp to see time of last refresh.
document.write(new Date());
</script>

答案 1 :(得分:1)

max_execution_time参数可以停止脚本,如果耗时太长,默认情况下为30秒,请参阅文档 - http://php.net/manual/en/info.configuration.php#ini.max-execution-time

您可以尝试在脚本开头set_time_limit(0)(请参阅http://php.net/manual/en/function.set-time-limit.php),或更改max_execution_time参数本身。

但总的来说,我不会采用这样的解决方案,它不是很可靠。更好地找到可以使用cron的托管,或者您可以尝试寻找一些外部服务,它将每隔5分钟ping您的脚本(可能您可以使用监视Web应用程序运行状况的服务)。

答案 2 :(得分:0)

试试这个解决方案:

<?php
$interval=5; //minutes
set_time_limit(0);
while (true)
{
$now=time();
include("alert_exe.php");
sleep($interval*05-(time()-$now));
}
?>

通过重新启动apache来停止脚本,或者从内部脚本构建一个返回值,该值随(true)变为while(false)