preface
Recently, scheduled tasks have been used in the project. Previously, we used Quartz to implement them. Recently, we found that Spring provides Spring Schedule to help us implement simple scheduled tasks. Here are two ways to use Spring Boot projects.
Spring Schedule implements scheduled tasks
Spring Schedule implements scheduled tasks in two ways: 1. Configure Scheduled tasks using XML. 2. Use @scheduled annotations. Because it is a Spring Boot project, it is possible to avoid using XML configuration form, mainly in the form of annotations.
Spring Schedule provides three forms of scheduled tasks:
Fixed wait time @Scheduled(fixedDelay = time interval)
@Component
public class ScheduleJobs {
public final static long SECOND = 1 * 1000;
FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
@Scheduled(fixedDelay = SECOND * 2)
public void fixedDelayJob() throws InterruptedException {
TimeUnit.SECONDS.sleep(2);
System.out.println("[FixedDelayJob Execute]"+fdf.format(new Date()));
}
}
Copy the code
Fixed interval @scheduled (fixedRate = interval)
@Component public class ScheduleJobs { public final static long SECOND = 1 * 1000; FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss"); @Scheduled(fixedRate = SECOND * 4) public void fixedRateJob() { System.out.println("[FixedRateJob Execute]"+fdf.format(new Date())); }}
Copy the code
Corn expression @scheduled (cron = Corn expression)
@Component
public class ScheduleJobs {
public final static long SECOND = 1 * 1000;
FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
@Scheduled(cron = "0/4 * * * * ?")
public void cronJob() {
System.out.println("[CronJob Execute]"+fdf.format(new Date()));
}
}
Copy the code
Spring Boot integrates Quartz for scheduled tasks
Adding Maven dependencies
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
Copy the code
Spring Boot with Quartz
Spring projects integrate Quartz by adding SchedulerFactoryBean to the FactoryBean, so add spring-Context-support to maven dependencies.
Start by adding the QuartzConfig class to declare the related beans
@Configuration public class QuartzConfig { @Autowired private SpringJobFactory springJobFactory; @Bean public SchedulerFactoryBean schedulerFactoryBean() { SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); schedulerFactoryBean.setJobFactory(springJobFactory); return schedulerFactoryBean; } @Bean public Scheduler scheduler() { return schedulerFactoryBean().getScheduler(); }}
Copy the code
Note here that I injected a custom JobFactory and set it to the JobFactory of the SchedulerFactoryBean. The reason for this is that I need Spring to inject some Service in a specific Job. So we need to customize a JobFactory that uses Spring’s API for dependency injection when instantiating a specific job class.
SpringJobFactory implementation:
@Component public class SpringJobFactory extends AdaptableJobFactory { @Autowired private AutowireCapableBeanFactory capableBeanFactory; @Override protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { Object jobInstance = super.createJobInstance(bundle); capableBeanFactory.autowireBean(jobInstance); return jobInstance; }}
Copy the code
Specific usage (taken from the project code) :
@Service
public class QuartzEventServiceImpl implements QuartzEventService {
private static final String JOB_GROUP = "event_job_group";
private static final String TRIGGER_GROUP = "event_trigger_group";
@Autowired
private Scheduler scheduler;
@Override
public void addQuartz(Event event) throws SchedulerException {
JSONObject eventData = JSONObject.parseObject(event.getEventData());
Date triggerDate = eventData.getDate("date");
JobDetail job = JobBuilder.newJob(EventJob.class).withIdentity(event.getId().toString(), JOB_GROUP).usingJobData(buildJobDateMap(event)).build();
Trigger trigger = TriggerBuilder.newTrigger().withIdentity(event.getId().toString(), TRIGGER_GROUP).startAt(triggerDate).build();
scheduler.scheduleJob(job, trigger);
}
Copy the code