• Java之监听某一字段状态的应用


    需求:

      某一张表中,新增时有时间,状态(初始为0)字段,要求到该时间时,就将该条数据的状态设置为1

    思路:

      做正常的增改,直接将这两个字段存入至数据库,然后再公共类中写监听,每2分钟将数据库中小于系统时间的字段设置为1

    代码:

      监听类: 

      public class SystemListener implements ServletContextListener {
        private Timer timer = null;

        public void contextDestroyed(ServletContextEvent arg0) {
          if (timer != null) {
            timer.cancel();
          }
        }

        public void contextInitialized(ServletContextEvent arg0) {
          if (timer == null) {
            System.out.println("审核监听开启...");
            timer = new Timer();
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 90);
            calendar.set(Calendar.SECOND, 0);

            //服务启动后1分钟后执行1次,之后2分钟执行一次
            timer.schedule(new SynJzbmsj(), 1000*60, 2*60*1000);
          }
        }
      }

      修改状态类:

      public class SynJzbmsj extends TimerTask{
        private Logger log = Logger.getLogger(SynJzbmsj.class);
        @Override
        public void run() {
          try{
            log.info("修改截至报名时间的状态");
            long time_s = System.currentTimeMillis();

            
            syn();

            long time_e = System.currentTimeMillis();
            log.info("修改截至报名时间的状态,耗时(ms):"+(time_e-time_s));
          } catch (Exception e) {
            e.printStackTrace();
          }
        }

        private void syn(){
          try{
            //修改学位项目中截至报名时间的状态

            String sql = "update WEB_XWXM set sjzt = '0' where JZBMSJ <= sysdate";

            DBManagerUtil db = new DBManagerUtil();
            db.execute(sql);

          }catch(Exception e){
            log.error("修改截至报名时间的状态时发生错误"+e.toString(), e);
            e.printStackTrace();
          }
        }

      }

      web.xml文件中配置监听器 

      <listener>
        <listener-class>
          yansoft.common.SystemListener
        </listener-class>
      </listener>

    自此大功告成!

  • 相关阅读:
    P1311 选择客栈 模拟 ( + st表)
    P2656 采蘑菇 tarjan + spfa
    送别
    10.16互测题 贪心+数论
    poj 2823 Sliding Window 单调队列
    P1036 选数 dfs
    P3370 【模板】字符串哈希
    A Tear or A Smile?
    KMP 算法
    jQuery 中 attr 和 prop 的区别
  • 原文地址:https://www.cnblogs.com/zying3/p/11016313.html
Copyright © 2020-2023  润新知