Defining a Custom Job
Create a job class that extends QuartzJobBean and implements the executeInternal method.
@Slf4j
public class MyJob extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
log.info("MyJob start...");
long start = System.currentTimeMillis();
MyService myService = (MyService) context.getMergedJobDataMap().get("myService");
try {
myService.func();
} catch (Exception e) {
log.error("MyJob error: ", e);
}
long end = System.currentTimeMillis();
log.info("MyJob end in {} ms", end - start);
}
}
Configuration
Define beans for JobDetail, CronTrigger, and SchedulerFactoryBean.
@Configuration
public class QuartzConfig {
@Setter(onMethod_ = {@Autowired})
private MyService myService;
@Bean
public JobDetailFactoryBean myJobDetail() {
JobDetailFactoryBean detail = new JobDetailFactoryBean();
detail.setJobClass(MyJob.class);
detail.setDurability(true);
Map<String, Object> jobData = new HashMap<>();
jobData.put("myService", myService);
detail.setJobDataAsMap(jobData);
return detail;
}
@Bean
public CronTriggerFactoryBean myJobTriggerBean() {
CronTriggerFactoryBean trigger = new CronTriggerFactoryBean();
trigger.setJobDetail(Objects.requireNonNull(myJobDetail().getObject()));
trigger.setCronExpression("*/5 * * * * ?"); // run every 5 seconds
return trigger;
}
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setTriggers(myJobTriggerBean().getObject());
return schedulerFactoryBean;
}
}
How It Works
SchedulerFactoryBean overrides the start() method of Spring's Lifecycle interface. When the Spring container initializes, start() is automatically called, activating the scheduled tasks.
JobDetailFactoryBean and CronTriggerFactoryBean implement both FactoryBean and InitializingBean. During afterPropertiesSet(), they create and populate the corresponding JobDetail and CronTrigger objects. The getObject() method then returns these initialized instances.