簡體   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