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>

自此大功告成!