SpringBoot整合Quartz
依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
Job:
@Component
public class MyFirstJob {
public void sayHello() {
System.out.println("MyFirstJob: hello!");
}
}
public class MySecondJob extends QuartzJobBean {
private String name;
public void setName(String name) {
this.name = name;
}
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("MySecondJob:hello " + name + ":" + new Date());
}
}
Job可以是一个普通的JavaBean,如果是普通的JavaBean,那么可以先添加@Component注解注册到容器。Job也可以继承抽象类QuartzJobBean,若继承自QuartzJobBean,则需要实现该类中的executeInternal方法,该方法在任务被调用时使用。
config:
@Configuration
public class QuartzConfig {
@Bean
public MethodInvokingJobDetailFactoryBean jobDetail() {
MethodInvokingJobDetailFactoryBean bean = new MethodInvokingJobDetailFactoryBean();
bean.setTargetBeanName("myFirstJob");
bean.setTargetMethod("sayHello");
bean.setName("job1");
bean.setGroup("group");
return bean;
}
@Bean
public JobDetailFactoryBean jobDetail2() {
JobDetailFactoryBean bean = new JobDetailFactoryBean();
bean.setJobClass(MySecondJob.class);
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("name", "test");
bean.setJobDataMap(jobDataMap);
bean.setDurability(true);
bean.setName("job2");
bean.setGroup("group");
return bean;
}
@Bean
public SimpleTriggerFactoryBean simpleTriggerFactoryBean() {
SimpleTriggerFactoryBean bean = new SimpleTriggerFactoryBean();
bean.setJobDetail(jobDetail().getObject());//关联job
bean.setRepeatCount(3);//实际执行4次
bean.setStartDelay(1000);
bean.setRepeatInterval(2000);
bean.setName("trigger1");
bean.setGroup("group");
return bean;
}
@Bean
public CronTriggerFactoryBean cronTriggerFactoryBean() {
CronTriggerFactoryBean bean = new CronTriggerFactoryBean();
bean.setJobDetail(jobDetail2().getObject());//关联job
bean.setCronExpression("0/2 * * * * ?");
bean.setName("trigger2");
bean.setGroup("group");
return bean;
}
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean bean = new SchedulerFactoryBean();
bean.setTriggers(simpleTriggerFactoryBean().getObject(), cronTriggerFactoryBean().getObject());
return bean;
}
}
启动: