아무거나

[Spring Boot] 스케줄링 구현 본문

Java/Spring

[Spring Boot] 스케줄링 구현

전봉근 2019. 1. 16. 18:14
반응형

스케줄링

  • Scheduler
    • Spring Boot에서 @EnableScheduling, @Scheduled를 사용한 스케줄링 구현
      • 메인 메소드가 있는 애플리케이션 구동 클래스인 Application.java에 @EnableScheduling 설정 및 @Bean 추가

        ....
        import org.springframework.scheduling.annotation.EnableScheduling;
        
        @SpringBootApplication
        @EnableScheduling
        public class Application {
        
            public static void main(String[] args) {
                ApplicationContext ctx = SpringApplication.run(Application.class, args);
            }
        
            @Bean
            public TaskScheduler taskScheduler() {
                // 단일 스레드 구현
                return new ConcurrentTaskScheduler();
            }
        
        }
        
      • 스케줄링을 적용시킬 클래스를 생성하고 메소드를 추가

        ....
        import org.springframework.scheduling.annotation.Scheduled;
        import org.springframework.stereotype.Component;
        
        @Component
        public class CronExample {
        
            // 매일 3시 20분 0초에 실행
            @Scheduled(cron = "0 20 3 * * *")
            public void exampleJob1() {
                // 실행할 로직1
            }
        
            // 매월 3일 0시 0분 0초에 실행
            @Scheduled(cron = "0 0 0 3 * *")
            public void exampleJob2() {
                // 실행할 로직2
            }
        
            // 3초마다 실행
            @Scheduled(fixedRate = 3000)
            public void exampleJob3() {
                // 실행할 로직3
            }
        
            // 애플리케이션 시작 후 30초 후에 첫 실행, 그 후 매 10초마다 주기적으로 실행
            @Scheduled(initialDelay = 30000, fixedDelay = 10000)
            public void exampleJob4() {
                // 실행할 로직4
            }
        
        }


반응형
Comments