我刚刚开始以动态方式创建Quartz Scheduled Jobs。因此,在QuartzConfig类中,我创建了一个SchedulerFactoryBean
,JobDetailFactoryBean
和CronTriggerFactoryBean
。其中Job和CronTrigger Bean是原型。
@Configuration
public class QuartzConfig {
@Autowired
ApplicationContext context;;
@Bean
public SchedulerFactoryBean quartzScheduler(){
SchedulerFactoryBean quartzScheduler = new SchedulerFactoryBean();
quartzScheduler.setOverwriteExistingJobs(true);
quartzScheduler.setSchedulerName("job-scheduler");
AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
jobFactory.setApplicationContext(context);
quartzScheduler.setJobFactory(jobFactory);
return quartzScheduler;
}
@Bean
@Scope(value = "prototype")
public JobDetailFactoryBean getJobBean(){
JobDetailFactoryBean bean = new JobDetailFactoryBean();
bean.setJobClass(DailyJob.class);
bean.setGroup("daily-group");
bean.setName("daily-name");
bean.setBeanName("daily-name");
bean.getJobDataMap().put("daily", "daily");
return bean;
}
@Bean
@Scope(value = "prototype")
// @Lazy(value = true)
public CronTriggerFactoryBean getCronTriggerBean(String cron){
CronTriggerFactoryBean bean = new CronTriggerFactoryBean();
bean.setCronExpression(cron);
bean.setJobDetail(getJobBean().getObject());
bean.setGroup("daily-group");
return bean;
}
}
在我的Controller类中,我想通过请求创建作业。我自动连线
SchedulerFactoryBean
将石英触发器设置为bean。@Controller
public class JobController {
@Autowired
SchedulerFactoryBean quartzScheduler;
@Autowired
ApplicationContext context;;
@ResponseBody
@RequestMapping("/job/create/daily")
public String dailyJob(){
CronTriggerImpl cron = (CronTriggerImpl) context.getBean("getCronTriggerBean","30 * * ? * MON-FRI");
Trigger[] triggers = { cron };
quartzScheduler.setTriggers(triggers);
return "dailyJob";
}
}
一切正常,而不会产生错误,并且
Job
和Trigger
设置为quartzScheduler
(在调试模式下查看)。但是工作从未运行过。我想念什么?并且不要忘记,有一个实现
Job
的类:@Component
public class DailyJob implements Job{
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("Daily Job runs!");
}
}
最佳答案
这是对我有用的东西:
@Controller
public class JobController {
@Autowired
private Scheduler scheduler;
@Autowired
private ApplicationContext context;
@ResponseBody
@RequestMapping("/job/create/daily")
public String dailyJob() throws SchedulerException {
JobDetail jobDetail = context.getBean(JobDetail.class);
Trigger cronTrigger = context.getBean(Trigger.class, "30 * * ? * MON-FRI");
scheduler.scheduleJob(jobDetail, cronTrigger);
return "dailyJob";
}
}
您必须使用
Scheduler
而不是SchedulerFactoryBean
,因为后者的目的是创建将在作业上运行的实际调度程序。另外,如果您使用
scheduler.scheduleJob(cron)
,则它不会安排作业,因为该作业尚未存储在作业存储中,因此您需要使用其详细信息来创建作业,并将cron表达式与其关联。