MySQL - Change field value after X minutes of inactivity

旧城冷巷雨未停 提交于 2019-12-11 03:37:18

问题


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)


回答1:


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.



来源:https://stackoverflow.com/questions/19477036/mysql-change-field-value-after-x-minutes-of-inactivity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!