Timer与TimerTask编写的定时器(在spring+struts2+mybatis框架下)

1 篇文章 0 订阅
1 篇文章 0 订阅

目录

Timer与TimerTask编写的定时器(在spring+struts2+mybatis框架下)


Timer与TimerTask编写的定时器(在spring+struts2+mybatis框架下)

代码如下

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class TimerAccounting implements ServletContextListener {

//	一天的毫秒
	long daySpan = 24 * 60 * 60 * 1000; 
	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	/**
	 * 定时器
	 */
	private Timer timer;
//初始化方法
	@Override
	public void contextInitialized(ServletContextEvent arg0) {
	
		// TODO Auto-generated method stub
//		初始定时器启动时间时分秒
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 10:42:00");
		Date startTime = null;
		try {
			startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf.format(new Date()));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/**
		 * 初始化定时器
		 * startTime 定时器启动时间
		 * daySpan 定时器延迟启动时间间隔
		 */
		timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				costAccounting();
				/* System.out.println("执行了1次"); */
			}
		}, startTime, daySpan);

	}
	
	//销毁定时器
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		timer.cancel();
	}

	public void costAccounting() {

		System.out.println("执行了1次");
		
		
		
		
	}
}

添加项目下WEBROOT->WEB-INF->web.xml

<!-- 要定期执行的任务 -->
<listener>
<!-- 你执行需要定时那个类路径 -->
	  <listener-class> com.bhlh.valueChain.action.TimerAccounting</listener-class></listener>

该定时器加载较早,继承listener可能初始化太早了,后期编写的别的功能类添加注入不进去

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值