The easiest way is to make some configuration by extending SpringBeanJobFactory and @Override
createJobInstance method. Then you need to define SchedulerFactoryBean and finally your Scheduler:
@Configuration
public class SchedulerConfiguration {
public class AutowireCapableBeanJobFactory extends SpringBeanJobFactory {
private final AutowireCapableBeanFactory beanFactory;
@Autowired
public AutowireCapableBeanJobFactory(AutowireCapableBeanFactory beanFactory) {
Assert.notNull(beanFactory, "Bean factory must not be null");
this.beanFactory = beanFactory;
}
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
Object jobInstance = super.createJobInstance(bundle);
this.beanFactory.autowireBean(jobInstance);
this.beanFactory.initializeBean(jobInstance, null);
return jobInstance;
}
}
@Bean
public SchedulerFactoryBean schedulerFactory(ApplicationContext applicationContext) {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setJobFactory(new AutowireCapableBeanJobFactory(applicationContext.getAutowireCapableBeanFactory()));
return schedulerFactoryBean;
}
@Bean
public Scheduler scheduler(ApplicationContext applicationContext) throws SchedulerException {
Scheduler scheduler = schedulerFactory(applicationContext).getScheduler();
scheduler.start();
return scheduler;
}
}
Then anywhere in your application, for example in a RestController you can access the scheduler and schedule a new job:
@RestController
public class ScheduleController {
@Autowired
private Scheduler scheduler;
@GetMapping(value = "/schedule/{detail}/{desc}")
public String scheduleJob(@PathVariable(value = "detail") String detail, @PathVariable(value = "desc") String desc) throws SchedulerException {
JobDetail job = newJob(detail, desc);
return scheduler.scheduleJob(job, trigger(job)).toString();
}
private JobDetail newJob(String identity, String description) {
return JobBuilder.newJob().ofType(SimpleJob.class).storeDurably()
.withIdentity(JobKey.jobKey(identity))
.withDescription(description)
.build();
}
private SimpleTrigger trigger(JobDetail jobDetail) {
return TriggerBuilder.newTrigger().forJob(jobDetail)
.withIdentity(jobDetail.getKey().getName(), jobDetail.getKey().getGroup())
.withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(1))
.build();
}
}
You can control all schedules (pause, stop, restart, delete, etc...) from your Scheduler
- look at the documentation