java的定时器实现

1主方法 服务器启动时开始调用启动




package com.casco.csmis.szdc.jxkp.task;

import java.util.Timer;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 类说明:
 * 
 * @ClassName: 码灵
 * @author ht_wangjun 在 Servlet API 中有一个 ServletContextListener 接口,它能够监听
 *         ServletContext 对象的生命周期,实际上就是监听 Web 应用的生命周期。 当Servlet 容器启动或终止Web
 *         应用时,会触发ServletContextEvent 事件,该事件由ServletContextListener 来处理。在
 *         ServletContextListener 接口中定义了处理ServletContextEvent 事件的两个方法。
 */
public class PerformanceTaskListener implements ServletContextListener {

	Log logger = LogFactory.getLog(PerformanceTaskListener.class);

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		logger.debug("tomcat 开始结束");
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		logger.debug("tomcat 开始");
		Timer timer = new Timer();
		CreatePerformanceTask task = new CreatePerformanceTask(arg0);
		// 这里每天执行一次,首次执行时间为200秒后
		timer.schedule(task, 1000 * 200, 1 * 24 * 3600 * 1000);
	}

}



2执行方法

package com.casco.csmis.szdc.jxkp.task;

import java.util.TimerTask;

import javax.servlet.ServletContextEvent;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.casco.csmis.szdc.jhgl.utils.CalUtils;
import com.casco.csmis.szdc.jxkp.dao.PerformanceInfoDao;
import com.casco.csmis.szdc.jxkp.model.PerformanceInfo;

/** 
 * 类说明: 定时器
 * @ClassName: CreatePerformanceTask
 */
@Component
public class CreatePerformanceTask extends TimerTask {
	/**
	 * 引入dao层
	 * @param arg0
	 */
	private PerformanceInfoDao performanceInfoDao;
	public CreatePerformanceTask(ServletContextEvent arg0) {
		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext());
		this.setPerformanceInfoDao((PerformanceInfoDao)ctx.getBean("performanceInfoDao"));
	}

	@Override
	public void run() {
		System.out.println("自动生成开始----------------------------:");
		String pararm;
		List<PerformanceInfo> infoList = performanceInfoDao.findPerformanceListByYearsAndQuarter(pararm);
		
		
	}

	public PerformanceInfoDao getPerformanceInfoDao() {
		return performanceInfoDao;
	}

	public void setPerformanceInfoDao(PerformanceInfoDao performanceInfoDao) {
		this.performanceInfoDao = performanceInfoDao;
	}
	
}
3配置:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码灵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值