我想在指定的时间间隔内连续运行以下 PHP 脚本,并且可以由用户使用表单进行设置.如何做到这一点


i want to run the following php script continously in specified intervals of time and can be set by a user using a form. how to do this?

//我需要重复运行此脚本,时间间隔可以由用户设置

检查互联网连接

if (!$sock = fsockopen("www.google.com", 80, $errno, $errstr,20))
    {
?>
<script type="text/javascript">
alert("Connection problem");
</script>
<?php       
    }

从数据库中检索数据并检查站点已关闭

else
    {
    for($i=0;$i<count($res);$i++)
        {
        $fp=fsockopen($res[$i]['url'],80,$errno,$errstr,30);
        if($fp==false)
            {
 ?>
 <script type="text/javascript">
 alert("Website is down");
 </script>
 <?php

将数据写入数据库并发送邮件

mail($email[0]['email_id'],"website is down",$res[$i]['url']." is down");
    $inputs=array('website_id'=>$res[$i['website_id'],
    'date'=>date("Y-m-d H:i:s"),'reason'=>"website down");
$obj3->addLog($inputs);
         }
    }
}
sleep(300);
}

查看cron服务。有人已经在这里解释过了。

如果你想让它保持网页的形式,自动重新加载自己,那么看看 JavaScript 函数setTimeout

您对 cron 的问题是这个"and the time interval can be set by a user".

您可以使用cron这样一种方式,即每 30 秒或每 N 秒运行一次脚本。这是运行脚本的最小粒度

现在,如果用户设置该脚本必须每 30 分钟运行一次,则在脚本中要做的第一件事是检查脚本是否需要继续 - 如果上次运行是在用户设置的 30 分钟之前。脚本伪像这样:

1) load last run from DB, compare it with interval - do we need to proceed, if not exit
2) do what script needs to do
3) save to the DB last run time

当然,只有当用户需要能够动态更改运行间隔并且不想接触 cron 时,这一切都是必要的。

有几种方法可以做到这一点。首先,您可以使用 cron 作业在设定的时间自动运行脚本。您的javascript将无法工作,因为PHP脚本将直接在服务器上运行,并且您将无法在浏览器中显示任何内容。

如果您希望用户在执行所有这些操作时打开页面,以便脚本可以在屏幕上报告数据,我只需将 URL 中的时间设置为 GET 参数mypage.php?refreshTime=1800,然后使用 $_GET['refreshTime'] 读取它,然后使用以下行设置刷新时间。

<meta http-equiv="refresh" content="$refreshTime">

这将导致页面在 $refreshTime 秒后重新加载。您的 PHP 执行它需要执行的任何操作都将在每次刷新时运行,就像现在加载页面时一样。