简体   繁体   中英

How can I repeat a mysql query every 5 minutes?

I have an sql query that looks like this:

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

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

    $content = $sql->fetch_assoc();

    $id = $content['id'];

    /* PHP Operations here. */
    ?>

Now, I want to be able to repeat this sql query every lets say 5 minutes, because the tables content will change. How can I do this? Is there a way to do an sql request in a javascript or ajax script?

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

Solution

Use a cron job. If the file you are showing is "/var/www/some/file.php" then just execute the following as the user which runs the web server (for example, "www-data" or "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

Assumptions

  • You're using Linux.
  • You're using apache httpd.

Background

PHP web applications are PHP scripts which are run by the web server in response to an HTTP request. What you need in here is to run the PHP script not in response to an HTTP request but in response to a time event, say, 5 minutes have passed since the last run.

Well, according to the Q&A the real problem would have a solution like this:

Files

  1. You have one PHP file which is directly requested by the user, which I will call "/index.php", located at "/var/www/index.php". This has the presentation of the page and some javascript.
  2. You have a second PHP file which is requested by the user indirectly, which I will call "/bg.php", located at "/var/www/bg.php". This file's content only has the routines to update the database and returns javascript code or something else.

index.php

Here you will have something like this:

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

Edit:

References

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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