Quartz整体架构
QuickStart
HelloJob.class
public class HelloJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("niu");
System.out.println(jobExecutionContext.getTrigger().getKey());
}
}
QuartzTest.class
public class QuartzTest {
public static void main(String[] args) {
try {
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
/* define the job and tie it to our HelloJob class*/
JobDetail jobDetail = newJob(HelloJob.class).withIdentity("job1", "group1").build();
JobDetail jobDetail2 = newJob(HelloJob.class).withIdentity("job2", "group1").storeDurably().build();
Trigger trigger = newTrigger().withIdentity("trigger1", "group1")
.startNow()
.withSchedule(SimpleScheduleBuilder
.repeatSecondlyForever(2)).build();
Trigger trigger2 = newTrigger()
.withIdentity("trigger2", "group1")
.forJob("job2","group1")
.startNow()
.withSchedule(CronScheduleBuilder
.cronSchedule("0/5 * * * * ?")).build();
//根据JOB和Trigger来调用
scheduler.scheduleJob(jobDetail, trigger);
//想要直接根据Trigger调用,必须先将job添加进scheduler
scheduler.addJob(jobDetail2,false);
scheduler.scheduleJob(trigger2);
scheduler.start();
TimeUnit.SECONDS.sleep(10);
scheduler.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Trigger
Cron表达式
quartz.properties
配置参数,详见官网
http://www.quartz-scheduler.org/documentation/quartz-2.3.0/configuration/
SpringBoot集成Quartz
Job
不管用下面哪种方式,Job都是要单独写的
public class Job1 extends QuartzJobBean {
@Autowired
HelloService helloService;
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
StringJoiner outStr=new StringJoiner(" | ")
.add("Job1")
.add(Thread.currentThread().getName())
.add(helloService.helloService())
.add(context.getTrigger().getKey().getName());
System.out.println(outStr);
}
}
第一种方式,将JobDetail与Trigger写在一个类中
@Component
public class JobInit {
//Quartz-starter,已经将Scheduler注入到IOC容器了,可以直接调用
@Autowired
Scheduler scheduler;
@PostConstruct
public void initJob() throws SchedulerException {
JobDetail job1Detail = JobBuilder.newJob(Job1.class)
.build();
Trigger trigger= TriggerBuilder.newTrigger()
.startNow()
.build();
scheduler.scheduleJob(job1Detail,trigger);
}
}
第二种方式,Jobdetail和Trigger全部交给Spring管理,Spring会自动整合调用
@Configuration
public class JobConfig {
@Bean
public JobDetail job1Detail(){
return JobBuilder.newJob(Job1.class)
.withIdentity("job1")
.storeDurably()
.build();
}
@Bean
public Trigger job1Trigger(){
return TriggerBuilder.newTrigger()
.forJob("job1")
.startNow()
.build();
}
}
推荐第一种写法,第二种写法如果任务太多,容易弄混