需求:
某一張表中,新增時有時間,狀態(初始為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>
自此大功告成!