Java

[Spring Boot] Spring Batch + scheduler 사용해 일정 주기로 실행 방법

cob 2023. 3. 24. 10:55

 

Spring Batch란?
 대용량 일괄처리의 편의를 위해 설계된 가볍고 포괄적인 배치 프레임워크다.

 

 


1. Gradle에 의존성 추가

implementation 'org.springframework.boot:spring-boot-starter-batch'
implementation 'org.springframework.boot:spring-boot-starter-quartz'
testImplementation 'org.springframework.batch:spring-batch-test'

 

 

 

 


2. BatchConfig.java 생성

@Slf4j
@Configuration
@EnableBatchProcessing
public class BatchConfig {

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;


    @Bean
    public Job job() {

        Job job = jobBuilderFactory.get("openAi")
                .start(step())
                .build();

        return job;
    }

    @Bean
    public Step step() {
        return stepBuilderFactory.get("step")
                .tasklet((contribution, chunkContext) -> {
                    /*
                      여기에 실행하고 싶은 로직 생성
                      
                    */
                    
                    return RepeatStatus.FINISHED;
                })
                .build();
    }
}

 

 

 

 


2. BatchScheduler.java 파일 생성

@Slf4j
@Component
public class BatchScheduler {

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private BatchConfig batchConfig;

    @Scheduled(cron = "0 0 6 * * *")
    public void runJob() {

        // job parameter 설정
        Map<String, JobParameter> confMap = new HashMap<>();
        confMap.put("time", new JobParameter(System.currentTimeMillis()));
        JobParameters jobParameters = new JobParameters(confMap);

        try {
            jobLauncher.run(batchConfig.job(), jobParameters);
        } catch (JobExecutionAlreadyRunningException | JobInstanceAlreadyCompleteException
                 | JobParametersInvalidException | org.springframework.batch.core.repository.JobRestartException e) {

            log.error(e.getMessage());
        }
    }
}

 

 

 

 


3. 애플리케이션 메인 클래스 수정

@EnableScheduling
@EnableBatchProcessing
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
public class CompanionApplication {
	public static void main(String[] args) {
		SpringApplication.run(CompanionApplication.class, args);
	}

}
  • @EnableScheduling, @EnableBatchProcessing를 추가한다.

 

반응형