Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use @Configuration and @EnableScheduling together with Spring Batch

Since "Only void-returning methods may be annotated with @Scheduled", how can I use Spring Batch and Spring Scheduler Task when I am using @Bean configuration instead of xml configuration? Below you can find my complete configuration file. It is running perfectly when I trigger from main() but only once. I want to add @Scheduled(fixedrate=9999) in order to evoke same job at certain frequency. As far as I can see, in order to do this, I was expected to add @Scheduled around step1 method but I can't as it returns different from void.

@Configuration
@EnableBatchProcessing
@EnableScheduling
public class BatchConfiguration {
       private static final Logger log = LoggerFactory
                     .getLogger(BatchConfiguration.class);

       @Bean
       @StepScope
       public FlatFileItemReader<Person> reader() {
              log.info(new Date().toString());
              FlatFileItemReader<Person> reader = new FlatFileItemReader<Person>();
              reader.setResource(new ClassPathResource("test_person_json.js"));
              reader.setLineMapper(new DefaultLineMapper<Person>() {
                     {
                           setLineTokenizer(new DelimitedLineTokenizer() {
                                  {
                                         setNames(new String[] {"firstName", "lastName" });
                                  }
                           });
                           setFieldSetMapper(new BeanWrapperFieldSetMapper<Person>() {
                                  {
                                         setTargetType(Person.class);
                                  }
                           });
                     }
              });
              return reader;
       }

       @Bean
       public ItemProcessor<Person, Person> processor() {
              return new PersonItemProcessor();
       }

       @Bean
       public ItemWriter<Person> writer(DataSource dataSource) {
              JdbcBatchItemWriter<Person> writer = new JdbcBatchItemWriter<Person>();
              writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<Person>());
              writer.setSql("INSERT INTO people (first_name, last_name) VALUES (:firstName, :lastName)");
              writer.setDataSource(dataSource);
              return writer;
       }

       @Bean
       public Job importUserJob(JobBuilderFactory jobs, Step s1,
                     JobExecutionListener listener) {
              return jobs.get("importUserJob").incrementer(new RunIdIncrementer())
                           .listener(listener).flow(s1).end().build();
       }

       @Bean
       public Step step1(StepBuilderFactory stepBuilderFactory,
                     ItemReader<Person> reader, ItemWriter<Person> writer,
                     ItemProcessor<Person, Person> processor) {
              return stepBuilderFactory.get("step1").<Person, Person> chunk(10)
.reader(reader).processor(processor).writer(writer).build();
       }

       @Bean
       public JdbcTemplate jdbcTemplate(DataSource dataSource) {
              return new JdbcTemplate(dataSource);
       }
}


//Question updated on Dec 3th 2015 with first suggestion
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class PersonScheduler {
    private Job myImportJob;
    private JobLauncher jobLauncher;

    @Autowired
    public PersonScheduler(JobLauncher jobLauncher, @Qualifier("myImportJob") Job myImportJob){
        this.myImportJob = myImportJob;
        this.jobLauncher = jobLauncher;
   }

   @Scheduled(fixedRate=9999)
   public void runJob{
       jobLauncher.run(myImportJob, new JobParameters());
   }
}
like image 978
Jim C Avatar asked Dec 01 '15 21:12

Jim C


People also ask

How do you run two jobs sequentially in Spring Batch?

Once context is initialized, either you can do - JobLauncher jobLauncher = (JobLauncher) ctx. getBean("jobLauncher"); or do Autowired for this JobLauncher bean in main class and launch specific jobs sequentially in specific sequential order by invoking , jobLauncher. run(job, jobParameters) .

What is @configuration in spring boot?

Spring @Configuration annotation is part of the spring core framework. Spring Configuration annotation indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application.

How do you dynamically schedule a Spring Batch job?

Spring Batch Scheduling: Spring Batch Jobs Scheduling You can configure Spring Batch Jobs in two different ways: Using the @EnableScheduling annotation. Creating a method annotated with @Scheduled and providing recurrence details with the job. Then add the job execution logic inside this method.

How can I get jobParameters in Spring Batch processor?

@Configuration @EnableBatchProcessing public class BatchConfiguration { // read, write ,process and invoke job } JobParameters jobParameters = new JobParametersBuilder(). addString("fileName", "xxxx. txt"). toJobParameters(); stasrtjob = jobLauncher.


1 Answers

Just create separate component, where you autowire your job and schedule it:

@Component
public class MyScheduler{
    private Job myImportJob;
    private JobLauncher jobLauncher;

    @Autowired
    public MyScheduler(JobLauncher jobLauncher, @Qualifier("myImportJob") Job myImportJob){
        this.myImportJob = myImoportJob; 
        this.jobLauncher = jobLauncher;
   }

   @Scheduled(fixedRate=9999)
   public void runJob(){
       jobLauncher.run(myImportJob, new JobParameters());
   }
}

Reaction on third comment:

Just use .allowStartIfComplete(true) when you are creating the step.

like image 145
luboskrnac Avatar answered Sep 30 '22 02:09

luboskrnac