포스트 목록

2016년 7월 8일 금요일

스프링 스케쥴러

이 게시물은 참조하지 않는 것을 권장합니다.

매일 아침마다 어떤 로직을 수행해야 한다고 해보자.

매번 해당 로직을 수행할 수 있게끔 어떤 장치가 필요할 것이다.

이런 수고를 덜어주는 기능을 발견했다.

스프링 스케쥴러(Spring Scheduler) 라고 부른다. 

-------------------------------------------------------------------------------------------------

  1. servlet-context.xml 에 추가
  2. service 에 추가


1. servlet-context.xml 에 추가

servlet-context.xml 에서 상단부분에 다음과 같이 task를 추가한다.
 (이클립스 개발 환경이라면, Namespaces 에서 task를 추가한다.)



<beans:beans xmlns:beans="http://www.springframework.org/schema/beans" 
                                    xmlns:context="http://www.springframework.org/schema/context" 
                                    xmlns:mvc="http://www.springframework.org/schema/mvc" 
                                    xmlns:task="http://www.springframework.org/schema/task" 
                                    xmlns:util="http://www.springframework.org/schema/util" 
                                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                                    xsi:schemalocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
  http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.2.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">
</beans:beans>

여기서 주목 할 점은 task 부분이다. (다른건 안봐도 괜찮다.)

그리고 이어서 스케줄러를 설정한다.


<task:scheduler id="taskScheduler"></task:scheduler>
<task:executor id="taskExecutor" pool-size="1"></task:executor>
<task:annotation-driven executor="taskExecutor" scheduler="taskScheduler"></task:annotation-driven>


2. service 에 추가

비즈니스 로직이 돌아갈 서비스에서 메소드를 만들고 해당 메소드에 다음 어노테이션을 추가한다.

@Scheduled(cron="* * * * * *") // 매 1초 마다 로직 수행
@Scheduled(cron="0 0/1 * * * *") // 매 1분 마다 로직 수행
@Scheduled(cron="0 30 9 * * *") // 매일 9시 30분 마다 로직 수행

cron에 들어가는 *은 매번 또는 계속 으로 해석해도 괜찮으며, 각가 "초 분 시 일 월 요일" 이다.



추가. 만약 위와 같이 했음에도 불구하고 로직이 수행되지 않는다면, 클래스 자체에 어노테이션이 붙어있는지 확인 하자. (ex. @Service, @Component ... )

댓글 없음:

댓글 쓰기