스프링 스케쥴러

최고고·2025년 5월 14일
0

스프링 웹프로젝트는
메인클래스 없어도 스케쥴러 돌릴 수 있음

  • WAS(Tomcat 등)가 메인역할을 함
  • 자바 애플리케이션은 메인클래스로 시작, 웹 프로젝트는 web.xml → DispatcherServlet → Spring 설정 로딩 순으로 동작.
    ---> 여기서 @Scheduled, @Service, @Component 등 스프링 빈들이 자동 등록되고 동작함.

스케줄러가 동작하는 흐름

  • web.xml에서 DispatcherServlet이나 ContextLoaderListener가 동작
  • applicationContext.xml / context-common.xml 같은 설정파일에서 <context:component-scan>, <task:annotation-driven> 등 스프링 설정 로딩
  • @Scheduled가 붙은 클래스가 @Component로 등록되어 있으면 스프링이 해당 클래스 빈으로 만들고, 자동으로 스케줄링 시작

@Scheduled가 실행이 안 되는 경우는 <task:annotation-driven /> 빠져 있거나, @Component 등록이 안 된 클래스일 가능성이 높음.

  1. java 기반 설정시
    클래스 생성후
    @Configuration
    @EnableScheduling
    어노테이션 달아줌

@Configuration
@EnableScheduling
public class SchedulerConfig {

}

➡️ applicationContext.xml / context-common.xml 같은 설정파일에 base-package 가 해당 클래스도 포함되어야함

  1. xml 설정시
    applicationContext.xml / context-common.xml 같은 설정파일에 아래 xmlns, task태그 생성
<!--task 네임스페이스 추가해야 함. -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/task 
           http://www.springframework.org/schema/task/spring-task-3.2.xsd">


<task:annotation-driven scheduler="scheduler" />
<task:scheduler id="scheduler" pool-size="5" />

스케쥴러클래스

@Component
public class Scheduler {

    @Scheduled(cron = "0 */5 * * * *")
    public void doTask() {
        ...
    }
}

0개의 댓글