1

I am new to Spring Batch, I have a Spring Boot App, and I want to set up a job that executes only once after Spring Boot app gets started, as we will run app each day

In my current solution, I tried to use attribute @Scheduled, but I am not sure what value it should have.

    @Scheduled(cron = "0/10 * * * * *")
    public void runMyJob() {
        jobLauncher.run(job, newExecution());
   }

    private JobParameters newExecution() {
        Map<String, JobParameter> parameters = new HashMap<>();
        JobParameter parameter = new JobParameter(new Date());
        parameters.put("currentTime", parameter);
        return new JobParameters(parameters);
    }
}


    @Bean
    public Step jobStep(ItemReader<ReadObject> reader,
                        ItemWriter<WriteObject> writer,
                        StepBuilderFactory stepBuilderFactory) {
        return stepBuilderFactory.get("jobStep1")
                .<ReadObject, WriteObject>chunk(1)
                .reader(reader)
                .writer(writer)
                .build();
    }

    @Bean
    public Job myJob(Step jobStep,
                          JobBuilderFactory jobBuilderFactory) {
        return jobBuilderFactory.get("myJob")
                .incrementer(new RunIdIncrementer())
                .flow(jobStep)
                .end()
                .build();
    }
}


@SpringBootApplication
@EnableBatchProcessing
@EnableScheduling
public class SpringBatchApplication {
    public static void main(String[] args) {
        try{
            SpringApplication.run(SpringBatchApplication.class, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
Szanownego
  • 239
  • 1
  • 11
  • Please check this question [here](https://stackoverflow.com/questions/27405713/running-code-after-spring-boot-st) – Ali.Wassouf Nov 24 '21 at 16:35
  • Does this answer your question? [Running code after Spring Boot starts](https://stackoverflow.com/questions/27405713/running-code-after-spring-boot-starts) – Ali.Wassouf Nov 24 '21 at 16:37
  • @Ali.Wassouf Nope, that question explains how to run something after spring boot start-up, but my question is more focused on Batch job. I am not sure which value @ Scheduled should have, and how I must call the job to start only once – Szanownego Nov 25 '21 at 06:30
  • This is probably because Spring Boot runs your job at startup a first time and then the `@Scheduled` method runs it a second time when the specified time arrives. Is that the case? Have you disabled the first run by Spring boot using `spring.batch.job.enabled=false`? – Mahmoud Ben Hassine Nov 26 '21 at 08:58

0 Answers0