728x90
반응형

* 일반적으로 전산실 환경에서 주기적인 디비 백업이나 메일 발송 기능은 유닉스 또는 리눅스 상에서의 cron을 이용하여 쉘 스크립트를 실행하는 형태로 구현한다. 현재 Spring Web MVC 3를 기반으로 개발 중인 사내 웹 애플리케이션에도 이런 형태의 스케줄 작업을 구현할 필요가 생겼는데 웹 애플리케이션 내부에서 구현해보자는 생각에 Spring 3 환경에서 Task Scheduler 메써드를 구현하는 방법을 조사해봤다.


* Spring 3에서는 어노테이션 기반으로 cron만큼 편리하고 직관적인 작업 스케줄러 기능을 지원한다.


* 적용할 Spring Web MVC 3 프로젝트가 XML 기반의 ApplicationContext로 구성되었다는 가정 하에 아래와 같이 task.xml 파일을 작성한다.

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans" 

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

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.1.xsd">

<task:annotation-driven executor="taskExecutor" scheduler="taskScheduler" />

<task:executor id="taskExecutor" pool-size="1" />

<task:scheduler id="taskScheduler" />

</beans>


* DispatcherServlet 역할을 하는 XML 파일에 아래 내용을 추가한다.

<import resource="task.xml" />


* 작업 스케줄러 메써드를 구현하기 위한 모든 준비가 끝났다. 이제 구현할 메써드를 @Service 클래스에 작성하면 된다. 방법은 간단하다. 특정 주기로 실행될 메써드 앞에 @Scheduled 어노테이션을 작성하면 된다.

@Scheduled(cron = "* * 1 * * ?") // 매일 오전 1시에 실행한다.

public void doSomething() {

  // doSomething

}


* 아래와 같이 다양한 주기 설정이 가능하다.

@Scheduled(fixedDelay = 3600000) // 1000 * 60 * 60, 즉 1시간마다 실행한다.


<참고자료>

Scheduled Jobs in Spring 3 (by Matt Young)

http://www.vodori.com/blog/spring3scheduler.html


Spring Framework 3.2 Reference Documentation: 27. Task Execution and Scheduling

http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html

 

@Scheduled(cron = "* * 1 * * ?") // 매일 오전 1시에 실행한다.
여기서 초, 분 부분이 0이 아니라 *일경우 매일 오전 1시 0분 0초부터 1시 59분 59초까지 1초에 한번씩 실행시킵니다.

다른 문서의 Scheduled 어노테이션의 cron 내용을 첨부합니다.

Cron Expression을 이용하여 Task 실행 주기 정의.

Cron Expression은 6개의 Field로 구성되며 각 Field는 순서대로 second, minute, hour, day, month, weekday를 의미한다. 각 Field의 구분은 Space로 한다. 또한 month와 weekday는 영어로 된 단어의 처음 3개의 문자로 정의할 수 있다.

0 0 * * * * : 매일 매시 시작 시점

*/10 * * * * * : 10초 간격

0 0 8-10 * * * : 매일 8,9,10시

0 0/30 8-10 * * * : 매일 8:00, 8:30, 9:00, 9:30, 10:00

0 0 9-17 * * MON-FRI : 주중 9시부터 17시까지

0 0 0 25 12 ? : 매년 크리스마스 자정

 

728x90
반응형
블로그 이미지

nineDeveloper

안녕하세요 현직 개발자 입니다 ~ 빠르게 변화하는 세상에 뒤쳐지지 않도록 우리모두 열심히 공부합시다 ~! 개발공부는 넘나 재미있는 것~!

,