前段时间,遇到的项目中,需要每隔一定的时间运行某些代码。刚开始想使用timer,后来得知有一种很实用的定时开源工具Quartz,经过摸索,发现Quartz即简单又实用。
我使用的Quartz版本为:quartz 2.2.0
使用Quartz的步骤为:
1. 定义定时任务类:
package org.lzstone.action
public class LzstoneTimeTask implements Job{
public void execute(JobExecutionContext context) throws JobExecutionException{
system.out.println("Quartz..");
}
}
2.启动定时任务分为程序直接启动和Web监听两种方式:
2.1.程序直接启动:
package org.lzstone.action;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
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 static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
LzstoneMain.run();
}
}
此方法会每隔一段时间触发你需要做的任务,但是启动后不会先执行一次,而是等到下一个执行时间点在执行,那么如果我们需要启动的时候就执行一次呢?
@SuppressWarnings("deprecation")
public static void run() {
try {
// 创建LzstoneTimeTask的定时任务
JobDetail jobDetail = new JobDetailImpl("lzstoneJob", Scheduler.DEFAULT_GROUP, CaptchSenderTask.class);
// 目标 创建任务计划
SimpleTrigger trigger = new SimpleTriggerImpl("lzstoneTrigger", null, new Date(), null,
SimpleTrigger.REPEAT_INDEFINITELY, Long.valueOf(setTime) * 1000L);
// 0 0 12 * * ? 代表每天的中午12点触发
sched = new org.quartz.impl.StdSchedulerFactory().getScheduler();
sched.scheduleJob(jobDetail, trigger);
sched.start();
} catch (SchedulerException e) {
e.printStackTrace();
logger.error(e.getMessage());
}
}
这样Quartz就会在程序启动时立即执行一次,后面按照设置的时间间隔执行任务。
2.2.Web监听方式:
package org.lzstone.action;
import javax.ejb.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class LzstoneMainListener implements ServletContextListener{
private Timer timer = null;
//初始化监听器,创建实例,执行任务
public void contextInitialized(ServletContextEvent event){
try {
LzstoneMain.run();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//销毁监听器,停止执行任务
public void contextDestroyed(ServletContextEvent event){
try {
LzstoneMain.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
web.xml配置:
<listener>
<listener-class>
org.lzstone.action.LzstoneMainListener
</listener-class>
</listener>