在springmvc框架下的三种定时器构建方法:
1.tomcat定时器,实现监听器接口并且继承TimerTask类,实现其run方法
1).建一个类重写TimerTask run方法:
class MyTask extends TimerTask{
@Override
public void run() {
//要定时执行的方法:
//弊端是方法不能调用spring容器,否则会报生成bean错误,因为bean只能被注入不能被new
System.out.println("hello greatjone !");
}
}
2).建一个监听器类实现ServlerContextListener接口
public class MyTimerTask implements ServletContextListener
{
private Timer timer = null;
public void contextDestroyed(ServletContextEvent event)
{
timer.cancel();
event.getServletContext().log("定时器销毁");
}
public void contextInitialized(ServletContextEvent event)
{
timer = new Timer(true);
event.getServletContext().log("定时器已启动");//添加日志,可在tomcat日志中查看到
Date date;
try {
date = new SimpleDateFormat("yyyy-MM-dd mm:ss").parse("2011-08-29 17:46");
//第一个参数是初始化我们上面继承timertask类的任务,第二个参数是从什么时候开始,第三个参数是间隔时间:单位是毫秒。
timer.schedule(new MyTask(),date,1*60*1000);
} catch (ParseException e) {
e.printStackTrace();
}
}
3)最后一步就是在web.xml文件中注册监听器
<listener>
<listener-class>监听类的全类名(第二步中的实现接口的累)</listener-class>
</listener>
2.通过spring框架实现定时器功能:第二种第三种发放都是基于spring的可以调用spring容器,一种是基于注解的一种是基于配置文件的,我们先来介绍基于注解的方式
这要求把定时任务注册成spring容器
1.在spring配置文件头上添加这三行
xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd
2.spring配置文件上添加任务定时扫描配置
<task:annotation-driven/>
3.添加扫描包
<context:component-scan base-package="定时任务所在的包的位置"/>
然后在编写定时任务
在类名之上添加spring容器注解:@Component(@Service)
在需要定时执行的方法上面添加@Scheculed注解
@Scheduled(cron=“0/30 * * * * ?)//cron表达式的用法可以参考:http://biaoming.iteye.com/blog/39532
public void test(){
}
3).第三种是基于配置文件的spring定时器用法
第一步
1.在spring配置文件头上添加这三行
xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd
2.spring配置文件上添加任务bean和task标签
<bean id="beanid" class="任务类的全类名"/>
<task:scheduled-tasks>
<task:scheduled ref="beanid" method="要定时执行的方法名" cron="0/60 * * * * ?"/>
<!--可配置多个方法-->
</task:scheduled-tasks>
第三种方法只通过配置文件就可以:但是要求和springbean要求一样:有无参构造方法,不能new其他对象。