我使用以下配置类将spring框架与Quartz集成,它工作正常,但是一旦应用程序启动就会动态触发,因为我使用@Configuration注释,我想通过控制器和ui手动触发作业,Can有谁告诉我,我该怎么办呢?
这是石英配置类
@Configuration
public class QuartzConfig {
@Autowired
private PlatformTransactionManager transactionManager;
@Autowired
private ApplicationContext applicationContext;
@Bean
public SchedulerFactoryBean quartzScheduler() {
SchedulerFactoryBean quartzScheduler = new SchedulerFactoryBean();
quartzScheduler.setTransactionManager(transactionManager);
quartzScheduler.setOverwriteExistingJobs(true);
AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
jobFactory.setApplicationContext(applicationContext);
quartzScheduler.setJobFactory(jobFactory);
Trigger[] triggers = {
processMyJobTrigger().getObject()
};
quartzScheduler.setTriggers(triggers);
return quartzScheduler;
}
@Bean
public JobDetailFactoryBean processMyJob() {
JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean();
jobDetailFactory.setJobClass(HelloJob.class);
jobDetailFactory.setDurability(true);
return jobDetailFactory;
}
@Bean
public CronTriggerFactoryBean processMyJobTrigger() {
CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
cronTriggerFactoryBean.setJobDetail(processMyJob().getObject());
cronTriggerFactoryBean.setCronExpression("0 0/1 * * * ?");
return cronTriggerFactoryBean;
}
}
Quartz job
@Service
@Transactional
public class HelloJob implements Job{
@Inject
TestrecordRepository testrecordRepository;
@Inject
ScoreRepository scoreRepository;
public void execute(JobExecutionContext context)
throws JobExecutionException {
System.out.println("Hello Quartz!");
List<Testrecord> records=testrecordRepository.findAll();
for(Testrecord t:records){
Testrecord testrecord = new Testrecord();
testrecord.setValue_integer(t.getValue_integer());
testrecord.setId(t.getId());
RuleExecutor ruleExecutor = new RuleExecutor();
Score score= ruleExecutor.processRules(testrecord);
scoreRepository.save(score);
}
}
}
答案 0 :(得分:0)
您只需要一个bean,您可以在其中注入调度程序和已有的工厂。例如:
@Service
public class QuartzService {
private Scheduler scheduler;
private CronTriggerFactoryBean cronTriggerFactory;
private JobDetailFactoryBean jobDetailFactory;
public void createJob() {
JobDetail job = jobDetailFactory.getObject();
Trigger trigger = cronTriggerFactory.getObject();
scheduler.scheduleJob(job, trigger);
}
// other methods: delete (unschedule), update (modify job), ...
// getters and setters
}
修改此类以使其符合您的要求。我使用像这样的类作为Web服务中的服务,但它可以在Web应用程序或其他任何东西中使用。
这个服务是由spring创建的,这意味着它必须在spring配置bean中定义:
@Bean
public QuartzService quartzService() {
QuartzService service = new QuartzService();
service.setScheduler(quartzScheduler());
service.setJobDetailFactoryBean(processMyJob());
service.setCronTriggerFactoryBean(processMyJobTrigger());
return service;
}