繁体   English   中英

如何每5分钟重复一次mysql查询?

[英]How can I repeat a mysql query every 5 minutes?

我有一个看起来像这样的sql查询:

<?php
    include("settings.php");

    $sql = conn->query("SELECT * FROM table LIMIT 1");

    $content = $sql->fetch_assoc();

    $id = $content['id'];

    /* PHP Operations here. */
    ?>

现在,我希望能够每隔5分钟重复一次此sql查询,因为表内容将更改。 我怎样才能做到这一点? 有没有办法在javascript或ajax脚本中执行sql请求?

如果只想刷新内容,则在settimeout()中使用AJAX调用。

使用cron作业。 如果您显示的文件是“ /var/www/some/file.php”,则只需以运行Web服务器的用户身份执行以下命令即可(例如,“ www-data”或“ apache”):

{
    # Will output to stdout the current user's crontab
  crontab -l;
    # Add a line to execute the php script every 5 minutes
  echo '*/5 * * * * '"$(which php5) /var/www/some/file.php";
} | crontab - # The current user's crontab will be replaced by stdin

假设条件

  • 您正在使用Linux。
  • 您正在使用apache httpd。

背景

PHP Web应用程序是由Web服务器响应HTTP请求而运行的PHP脚本。 这里您需要的是运行PHP脚本,而不是响应HTTP请求,而是响应时间事件,例如,自上次运行以来已经过去了5分钟。

好吧,根据问答, 真正的问题将有一个这样的解决方案:

档案

  1. 您有一个直接由用户请求的PHP文件,我将其称为“ /index.php”,位于“ /var/www/index.php”。 这里有页面的介绍和一些javascript。
  2. 您有第二个由用户间接请求的PHP文件,我将其称为“ /bg.php”,位于“ /var/www/bg.php”中。 该文件的内容仅具有更新数据库并返回javascript代码或其他内容的例程。

index.php

在这里,您将看到以下内容:

<script type="text/javascript">
/* Have jquery included before */

function poll_the_server(){
    /* Get the data from the server with ajax */
  var jqxhr = $.ajax( "/bg.php" )
    .always(function(){
         /* Prepare the next run */
        setTimeout(poll_the_server, 300);
      })
    .done(function(){
        /* Succeded: Do whatever you want with your data */
      })
    .fail(function(){
        /* Error: you may ask the user what to do */
      });
}

  /* Do the first call */
setTimeout(poll_the_server, 300);
</script>

编辑:

参考文献

http://api.jquery.com/jquery.ajax/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM