java定时器怎么写_java定时器代码该怎么写?

Java中定时器的实现小伙伴们了解过吗?对于一些特殊的代码是需要定时执行的,下面来看看定时器该如何编写吧。

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

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);

}

}

执行方法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  infoList = performanceInfoDao.findPerformanceListByYearsAndQuarter(pararm);

}

public PerformanceInfoDao getPerformanceInfoDao()

{

return performanceInfoDao;

}

public void setPerformanceInfoDao(PerformanceInfoDao performanceInfoDao)

{

this.performanceInfoDao = performanceInfoDao;

}

}

以上就是本篇文章的所有内容,更多java基础知识可以继续关注本站了解详情。

推荐阅读:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值