quartz.2.1.x任务调度
quartz2.1.x多任务执行案例
1.添加jar包
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.1.0</version>
</dependency>
2.创建任务
/**
* 添加任务
* @param scheduler
* @param jobName
* @param jobGroup
* @param cron
*/
private void addJob(Scheduler scheduler, String jobName, String jobGroup, String cron){
try {
JobDetail jobOne = JobBuilder.newJob(GbSimpleJob.class).withIdentity(jobName, jobGroup).build();
CronTrigger trgOne = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup)
.withSchedule(CronScheduleBuilder.cronSchedule(cron)) // [0 0/1 * * * ?]每一分钟执行一次
.forJob(jobName, jobGroup).build();
scheduler.scheduleJob(jobOne, trgOne);
} catch (ParseException e) {
e.printStackTrace();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
GbSimpleJob代码
package com.gbsoft.quartz.gbsoft; import java.text.SimpleDateFormat; import java.util.Date; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.JobKey; /** * @description GbSimpleJob * @class GbSimpleJob * @author 不了了之 * @date 2012-11-9 */ public class GbSimpleJob implements Job { private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * 执行任务 */ @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { System.out.println("start job 任务开始,时间:" + sdf.format(new Date())); JobKey jobKey = jobExecutionContext.getJobDetail().getKey(); System.out.println("任务---名称:" + jobKey.getName() + ",分组:" + jobKey.getGroup()); System.out.println("内容暂无!"); System.out.println("end job"); } }
3.添加多个任务private void one(){ try { Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); addJob(scheduler, "job1", "jobGroup1", "0 0/1 * * * ?"); addJob(scheduler, "job2", "jobGroup2", "0 0/2 * * * ?"); scheduler.start(); scheduler.pauseJob(new JobKey("job1","jobGroup1")); } catch (SchedulerException e) { e.printStackTrace(); }
4.测试main方法/** * @param args */ public static void main(String[] args) { System.out.println("测试开始"); SchedulerHelper test = new SchedulerHelper(); test.one(); System.out.println("测试结束"); }