예제로 배우는 핵심 Spring Batch

Ch09. 배치 작업 실행 하기 (스프링 스케줄링)

webmaster 2023. 6. 12. 00:18
728x90

https://spring.io/blog/2020/11/10/new-in-spring-5-3-improved-cron-expressions

 

New in Spring 5.3: Improved Cron Expressions

If you regularly listen to A Bootiful Podcast, you might have heard about the improvements we made to Spring Framework’s cron support. Cron expressions are mostly used in Spring applications through the @Scheduled annotation. In Spring 5.3, we introduced

spring.io

application.yml

#default
spring:
  profiles:
    active: local

---
spring:
  config:
    activate:
      on-profile: local
  batch:
    job:
      names: ${job.name:NONE}
      enabled: false #파라미터가 존재하더라도, Job이 실행되지 않는다.
    jdbc:
      initialize-schema: always # ?????
  datasource:
    url: "jdbc:h2:mem:batch;DB_CLOSE_ON_EXIT=FALSE"
    username: "sa"
    password: ""
    driver-class-name: org.h2.Driver
  jpa:
    show-sql: true

---
spring:
  config:
    activate:
      on-profile: test
  jpa:
    database: h2
  • spring.batch.job.enabled 옵션을 false로 주어 파라미터가 전달이 되더라도, Job이 실행되지 않도록 한다.

SpringBatchTutorialApplication

@EnableScheduling
@SpringBootApplication
@EnableBatchProcessing
public class SpringBatchTutorialApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringBatchTutorialApplication.class, args);
  }

}
  • @EnableScheduling 어노테이션을 추가한다.

SampleScheduler

@Component
public class SampleScheduler {

  @Autowired
  private Job helloWorldJob;

  @Autowired
  private JobLauncher jobLauncher;


  @Scheduled(cron = "0 */1 * * * *")
  public void helloWorldJobRun()
      throws JobInstanceAlreadyCompleteException, JobExecutionAlreadyRunningException, JobParametersInvalidException, JobRestartException {
    JobParameters jobParameters = new JobParameters(
        Collections.singletonMap("requestTime", new JobParameter(System.currentTimeMillis())));
    jobLauncher.run(helloWorldJob, jobParameters);
  }
}

cron 정규식

  •  Scheduled 안에 들어가는 cron 정규식은 위에 공식문서에 사용법이 나와있다.
    • 0 = 초, */1 = 1분마다, * = 모든 시간, * = 모든 일, * = 모든 월, * = 모든 요일(월~일)
  • JobParameters에 원하는 파라미터를 넣고, Job을 실행할 때 파라미터로 넘겨줄 수 있다.
  • jobLauncher의 run 메서드를 통해 Job을 실행한다.

 

728x90