示例版本:quartz2.3.2
原因:试下新版本api。复习下这块知识,以前写过一篇,太烂了
1、简单定时。
Scheduler defaultScheduler = null;
try {
defaultScheduler = StdSchedulerFactory.getDefaultScheduler();
logger.info("");
defaultScheduler.start();
JobDetail job = JobBuilder.newJob(SimpleJob.class).withIdentity("job1", "group1").build();
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1").startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(4).repeatForever()).build();
defaultScheduler.scheduleJob(job, trigger);
Thread.sleep(60000);
defaultScheduler.shutdown();
} catch (SchedulerException e) {
e.printStackTrace();
} finally {
if (defaultScheduler != null) {
try {
defaultScheduler.shutdown();
} catch (SchedulerException e1) {
e1.printStackTrace();
}
}
}
2、cron表达式定时
Scheduler defaultScheduler = null;
try {
defaultScheduler = StdSchedulerFactory.getDefaultScheduler();
logger.info("");
defaultScheduler.start();
JobDetail job = newJob(SimpleJob.class).withIdentity("job1", "group1").build();
CronTrigger build = newTrigger().withIdentity("trigger1", "group1")
.withSchedule(cronSchedule("0/2 * * * * ?")).build();
defaultScheduler.scheduleJob(job, build);
Thread.sleep(60000);
defaultScheduler.shutdown();
} catch (SchedulerException e) {
e.printStackTrace();
} finally {
if (defaultScheduler != null) {
try {
defaultScheduler.shutdown();
} catch (SchedulerException e1) {
e1.printStackTrace();
}
}
}
3、参数传递及job内改变参数。
主代码:
StdSchedulerFactory stdSchedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = stdSchedulerFactory.getScheduler();
JobDetail job1 = JobBuilder.newJob(ColorJob.class).withIdentity("job1", "group1").build();
job1.getJobDataMap().put(EXECUTION_COUNT, 0);
job1.getJobDataMap().put(FAVORITE_COLOR, "RED");
SimpleTrigger trigger1 = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1").startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(3).withRepeatCount(4)).build();
scheduler.scheduleJob(job1, trigger1);
scheduler.start();
Job代码:
/**
* 不允许作业的多个实例同时运行(请考虑以下情况:该作业的execute()方法中包含需要运行34秒的代码,但使用触发器,每30秒重复一次
* @author back
*
*/
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class ColorJob implements Job{
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
String color = dataMap.getString(FAVORITE_COLOR);
System.out.println("color:"+color);
int count = dataMap.getInt(EXECUTION_COUNT);
System.out.println("count : "+count);
count++;
dataMap.put(EXECUTION_COUNT, count);
try {
TimeUnit.MICROSECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
4、定时任务中产生异常。下面代码是异常后重新执行任务(一直执行),e2.unscheduleAllTriggers();这样设置后,异常就不会重新执行了
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class ExceptionJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
try {
int zero = 0;
int calculation = 4815 / zero;
} catch (Exception e) {
JobExecutionException e2 = new JobExecutionException(e);
// this job will refire immediately
e2.refireImmediately();
// e2.unscheduleAllTriggers();
throw e2;
}
}
}
5、多个任务执行顺序。
主逻辑
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
JobDetail job = JobBuilder.newJob(LogJob.class).build();
// Calculate the start time of all triggers as 5 seconds from now
Date startTime = DateBuilder.futureDate(5, IntervalUnit.SECOND);
// First trigger has priority of 1, and will repeat after 5 seconds
Trigger trigger1 = newTrigger()
.withIdentity("PriorityNeg5Trigger5SecondRepeat")
.startAt(startTime)
.withSchedule(simpleSchedule().withRepeatCount(1).withIntervalInSeconds(5))
.withPriority(1)
.forJob(job)
.build();
// Second trigger has default priority of 5 (default), and will repeat after 10 seconds
Trigger trigger2 = newTrigger()
.withIdentity("Priority5Trigger10SecondRepeat")
.startAt(startTime)
.withSchedule(simpleSchedule().withRepeatCount(1).withIntervalInSeconds(10))
.forJob(job)
.build();
// Third trigger has priority 10, and will repeat after 15 secondsTrigger trigger3 = newTrigger()
Trigger trigger3 = newTrigger().withIdentity("Priority10Trigger15SecondRepeat")
.startAt(startTime)
.withSchedule(simpleSchedule().withRepeatCount(1).withIntervalInSeconds(15))
.withPriority(10)
.forJob(job)
.build();
// Tell quartz to schedule the job using our trigger
sched.scheduleJob(job, trigger1);
sched.scheduleJob(trigger2);
sched.scheduleJob(trigger3);
sched.start();
Job逻辑
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class LogJob implements Job{
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
TriggerKey key = context.getTrigger().getKey();
String triggerName = key.getName();
System.out.println("trigger : "+triggerName);
}
}
看到顺序,所以定义为单线程执行。quartz。properties
org.quartz.scheduler.instanceName=PriorityExampleScheduler
# Set thread count to 1 to force Triggers scheduled for the same time to
# to be ordered by priority.
org.quartz.threadPool.threadCount=1
org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool
org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore
结论:先按顺序执行第一遍。执行完第一遍按照时间差完成第二遍