Skip to content

Instantly share code, notes, and snippets.

@virgium03
Created October 8, 2015 12:52
Show Gist options
  • Save virgium03/acb0bb3caa1f6818f2f3 to your computer and use it in GitHub Desktop.
Save virgium03/acb0bb3caa1f6818f2f3 to your computer and use it in GitHub Desktop.
Spring Batch Quartz scheduler configuration
@Configuration
@EnableBatchProcessing
class BatchConfiguration {
@Autowired
private JobRepository jobRepository;
@Value("${job.cron.expression}")
private String cronExpression;
@Autowired
private DataSource dataSource;
@Bean
SimpleJobLauncher jobLauncher() {
SimpleJobLauncher launcher = new SimpleJobLauncher();
launcher.setJobRepository(jobRepository);
launcher.setTaskExecutor(new SimpleAsyncTaskExecutor());
return launcher;
}
@Bean
JobRegistry jobRegistry() {
return new MapJobRegistry();
}
@Bean
JobExplorerFactoryBean jobExplorer() {
final JobExplorerFactoryBean jobExplorer = new JobExplorerFactoryBean();
jobExplorer.setDataSource(dataSource);
return jobExplorer;
}
@Bean
JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor() {
final JobRegistryBeanPostProcessor processor = new JobRegistryBeanPostProcessor();
processor.setJobRegistry(jobRegistry());
return processor;
}
@Bean
JobDetailFactoryBean unfileDocumentsJob() throws Exception {
JobDetailFactoryBean bean = new JobDetailFactoryBean();
bean.setJobClass(JobLauncherDetails.class);
bean.setGroup("quartz-batch");
final JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("jobName", DocsRoomConstants.UNFILE_HERMES_DOCUMENTS_JOB_NAME);
jobDataMap.put("jobLocator", jobRegistry());
jobDataMap.put("jobLauncher", jobLauncher());
bean.setJobDataMap(jobDataMap);
return bean;
}
@Bean
@Conditional(EnableSchedulerCondition.class)
SchedulerFactoryBean schedulerFactoryBean() throws Exception {
SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
factoryBean.setExposeSchedulerInRepository(true); // for java melody
factoryBean.setTriggers(cronTriggerBean().getObject());
Properties properties = new Properties();
properties.setProperty(SchedulerFactoryBean.PROP_THREAD_COUNT, "2");
factoryBean.setQuartzProperties(properties);
return factoryBean;
}
@Bean
CronTriggerFactoryBean cronTriggerBean() throws Exception {
CronTriggerFactoryBean bean = new CronTriggerFactoryBean();
bean.setJobDetail(unfileDocumentsJob().getObject());
bean.setCronExpression(cronExpression);
return bean;
}
/**
* Enable the Quartz scheduler only when a certain property is true.
*/
private static class EnableSchedulerCondition implements Condition {
@Override
public boolean matches(final ConditionContext context, final AnnotatedTypeMetadata metadata) {
return context.getEnvironment() != null && "true".equalsIgnoreCase(context
.getEnvironment().getProperty("job.enable.scheduling", "false"));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment