Search code examples
phpmysqlcron-task

MySQL - Change field value after X minutes of inactivity


I am trying to find a way to have a cronjob which checks how long it has passed since the last update of a row, if it is more than X, then change field 'ACTIVE' to 'FALSE'.

I have a robot which updates its current IP and add the timestamp.

From the other side, there might be a User willing to send commands to the robot. My idea is to be able to tell whether the robot has been active in the last X seconds and therefore it makes sense trying to send a command to it.

So, I guess some sort of script which checks if current_time() - field_time >= X then changeValue('ACTIVE')<- False.

Can this be done directly on the DB every X seconds? Or perhaps using a script in PHP a better way to handle this problem? (a script which loops indefinitely)


Solution

  • Try doing this with MySQL scheduling:

      DELIMITER $$
      CREATE EVENT deactivation
        ON SCHEDULE EVERY 10 MINUTE STARTS CURRENT_TIMESTAMP
        DO
          BEGIN
            UPDATE tbl SET tbl.active = FALSE
               WHERE tbl.active = TRUE AND 
               ( TIME_TO_SEC( TIMEDIFF (NOW(),tbl.updated) ) / 60 ) > 10;
          END;
      $$;
    

    Where tbl.updated is your timestamp (generated with php). As my testbox is unreachable atm, Im not sure if this query is correct, but generally, it should do the job.