这里Listener和随项目启动的servlet都可以随着项目启动而启动,只是启动的时序有所不同:
接下来分别实现下:
1.Listener实现:看代码
package com.web.cloudAgent.servlet; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class LoadBalanceListener implements ServletContextListener { private MyThread myThread; @Override public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub if (myThread != null && myThread.isInterrupted()) { myThread.interrupt(); } } @Override public void contextInitialized(ServletContextEvent arg0) { // TODO Auto-generated method stub String str = null; if (str == null && myThread == null) { myThread = new MyThread(); myThread.start(); } } } /** * 自定义一个 Class 线程类继承自线程类,重写 run() 方法,用于从后台获取并处理数据 */ class MyThread extends Thread { public void run(){ while (!this.isInterrupted()) {// 线程未中断执行循环 try { Thread.sleep(2000); //每隔2000ms执行一次 System.out.println("定时执行"); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 System.out.println(df.format(new Date()));// new Date()为获取当前系统时间 } catch (InterruptedException e) { e.printStackTrace(); } } } }