Самый простой способ - выполнить настройку, расширив метод SpringBeanJobFactory и @Override
createJobInstance . Затем вам нужно определить SchedulerFactoryBean и, наконец, ваш Планировщик :
@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;
}
}
Затем в любом месте вашего приложения, например, в RestController, вы можете получить доступ к планировщику и запланировать новое задание:
@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();
}
}
Вы можете контролировать все расписания (пауза, остановка, перезапуск, удаление и т. Д.) Из своего Scheduler
- просмотра документации