title: What's the best practice for PHP to continuously check for changes in the database?
body: <p>I am building a backend module (written in PHP) that will be used for <strong>monitoring private chat rooms that has no activity for [Exactly] 300 seconds (5 minutes)</strong>. If it is, the script will update the database (sets the max users to a certain number, and other stuffs). I am monitoring the span of idle time by the time difference of now() and last message sent.</p>
  
  <hr>
  
  <p>What I did: set a cron job that will run (through php-cli) my monitoring script every minute or 60 seconds. Inside the monitoring script:</p>
  
  <pre><code>$expire_time = time() + 60;
  
  //this loop will run for 60 seconds
  while(time() &lt; $expire_time)
  {
    $idle_time = get_all_chatrooms_idle_time();
    foreach($idle_time as $s_time)
    {
      if($s_time &gt;= 300)
      {
        update_changes();
      }
    }
    usleep(500000);
  }
  </code></pre>
  
  <hr>
  
  <p>The condition of instantly setting max users after 300 seconds idle time can't be bargained. So I cant really follow advice like: "avoid doing anything until something actually asks for it" even though it makes a lot of sense.</p>
  
  <p>Reason? The data of active and inactive chatrooms need to be real time because it will also be displayed on a dashboard. The chatroom moderators' pay depends on it.</p>
  
  <hr>
  
  <p>Why not check them every dashboard load? I'm sorry but still not possible.</p>
  
  <p>The checking needs to be server side and the dashboard updates itself with ajax, polling every second.</p>
  
  <p>When I attach the monitoring code to the page being requested by my ajax calls I think it's more resource intensive than my current implementation (correct me if Im wrong)</p>
  
  <p>Let me give you some rough estimate on the number of users so you can imagine the load/traffic we're getting:</p>
  
  <ul>
  <li>number of chatters including moderators: ~800</li>
  <li>number of chatrooms: ~250</li>
  <li>(x) number of chatroom moderators: ~50</li>
  <li>(x) my boss and his staff: </li>
  </ul>
  
  <p>(x) - can view the dashboard</p>
  
  <hr>
  
  <p>Is there a better way? Am I doing it right?</p>