2.java中常见的定时器
1)借助Java.util.Timer来实现
2)OpenSymphony社区提供的Quartz来实现
3.介绍Timer
利用Timer开发定时任务是主要分为两个步骤:
1)创建定时任务类
示例代码:
package org.lzstone.action
import java.util.TimeTask
public class LzstoneTimeTask extends TimeTask{
public void run(){
//执行的定时器任务
}
}
2)运行定时任务,运行定时任务分为两种方式:
2.1)程序直接启动
示例代码:
package org.lzstone.action
public class LzstoneMain{
.......
public void run(){
//执行定时器的任务
//创建实例
Timer timer = new Timer();
参数:
new LzstoneTimeTask()- 所要安排的任务。
0- 执行任务前的延迟时间,单位是毫秒。
1*1000- 执行各后续任务之间的时间间隔,单位是毫秒。
timer.schedule(new LzstoneTimeTask(),0,1*1000);
}
}
2.2)web监听方式
示例代码:
package org.lzstone.action
public class LzstoneMain implements ServletContextListener{
private Timer timer = null;
//初始化监听器,创建实例,执行任务
public void contextInitialized(ServletContextEvent event){
timer = new Timer();
timer.schedule(new LzstoneTimeTask(),0,1*1000);
}
//销毁监听器,停止执行任务
public void contextDestroyed(ServletContextEvent event){
//注意,在此计时器调用的计时器任务的 run 方法内调用此方法,就可以绝对确保正在执行的任务是此计时器所执行的最后一个任务。
timer.cancel();
}
}
web.xml配置
org.lzstone.action.LzstoneMain
4. 介绍Quartz
Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,可以用来创建简单或者复杂的定时任务,利用Quartz开发定时任务的步骤与Timer类
似。
利用Quartz开发定时任务是主要分为两个步骤:
1)创建定时任务类
示例代码:
package org.lzstone.action
public class LzstoneTimeTask implements Job{
public void execute(JobExecutionContext context) throws JobExecutionException{
//执行的定时器任务
}
}
2)运行定时任务,运行定时任务分为两种方式:
2.1)程序直接启动,创建任务调度器及配置相应的任务计划
示例代码:
package org.lzstone.action
public class LzstoneMain{
private static Scheduler sched;
public static void run() throws Exception{
//创建LzstoneTimeTask的定时任务
JobDetail jobDetail = new JobDetail("lzstoneJob",sched.DEFAULT_GROUP,LzstoneTimeTask.class);
//目标 创建任务计划
CronTrigger trigger = new CronTrigger("lzstoneTrigger","lzstone","0 0 12 * * ?");
//0 0 12 * * ? 代表每天的中午12点触发
sched = new org.quartz.impl.StdSchedulerFactory().getScheduler();
sched.scheduleJob(jobDetail,trigger);
sched.start();
}
//停止
public static void stop() throws Exception{
sched.shutdown();
}
}
//执行
public class Main{
.............
public void run(){
LzstoneMain.run();
}
............
}
2.2)web监听方式
示例代码:
package org.lzstone.action
public class LzstoneMainListener implements ServletContextListener{
private Timer timer = null;
//初始化监听器,创建实例,执行任务
public void contextInitialized(ServletContextEvent event){
LzstoneMain.run();
}
//销毁监听器,停止执行任务
public