스프링 웹프로젝트는
메인클래스 없어도 스케쥴러 돌릴 수 있음
스케줄러가 동작하는 흐름
- web.xml에서 DispatcherServlet이나 ContextLoaderListener가 동작
- applicationContext.xml / context-common.xml 같은 설정파일에서 <context:component-scan>, <task:annotation-driven> 등 스프링 설정 로딩
- @Scheduled가 붙은 클래스가 @Component로 등록되어 있으면 스프링이 해당 클래스 빈으로 만들고, 자동으로 스케줄링 시작
@Scheduled가 실행이 안 되는 경우는 <task:annotation-driven /> 빠져 있거나, @Component 등록이 안 된 클래스일 가능성이 높음.
@Configuration
@EnableScheduling
public class SchedulerConfig {
}
➡️ applicationContext.xml / context-common.xml 같은 설정파일에 base-package 가 해당 클래스도 포함되어야함
<!--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() {
...
}
}