java web定时器Timer

public class AutoRun implements ServletContextListener {
	protected final Log log = LogFactory.getLog(getClass());
	private Timer timer = null;
	private static TGroupBuyService service;
	private static ApplicationContext context;
	
	public void contextInitialized(ServletContextEvent arg0) {
		context =  WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext());
		service =(TGroupBuyService)context.getBean("groupBuyService"); 
		// TODO Auto-generated method stub
		timer = new Timer(true);
		try {
			
			// 一天的毫秒数
			 long daySpan = 24 * 60 * 60 * 1000;
			 
			 // 规定的每天时间10:00:00运行
			 final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd '10:00:00'");
			 // 首次运行时间
			 Date startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf.format(new Date()));
			 
			 // 如果今天的已经过了 首次运行时间就改为明天
			 if(System.currentTimeMillis() > startTime.getTime())
			  startTime = new Date(startTime.getTime() + daySpan);

			// 以每24小时执行一次
			 timer.scheduleAtFixedRate(new MyTask(), startTime, daySpan);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//timer .cancel();
	}
	
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		
		
	}
	
	class MyTask extends java.util.TimerTask {
		public void run() {
			log.info("--------------每天10点钟更新--------------");
			String[] id_Array = {"1","2","3"};
			String[] total_Array = {"10","6","6"};
			boolean flag = service.updateRemainder(id_Array, total_Array);
			if(flag){
				log.info("--------------定时器Job更新成功--------------");
			}else{
				log.info("--------------定时器Job更新失败--------------");
			}
		}
	}

	

}

你可能感兴趣的:(Java Web)