자바에서 스케줄러를 이용하여 정기적으로 동작을 수행 하는 방법을 알아 보겠습니다.


실습환경

- JDK 8

- Spring 5.0.8, XML 기반


환경설정(mvc-config.xml)

XML을 기반으로 하는 예제임으로 web.xml에 연결된 정보를 아래와 같이 기술 합니다.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
    xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.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/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/task 
        http://www.springframework.org/schema/task/spring-task.xsd">

    <annotation-driven>
        <argument-resolvers>
            <beans:bean class="org.springframework.mobile.device.DeviceWebArgumentResolver" />
        </argument-resolvers>
    </annotation-driven>
    
    <context:component-scan base-package="kr.jnu" />
    
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/view/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>
    
    <resources location="/resources/" mapping="/resources/**"/>
    <resources location="/favicon.ico" mapping="/favicon.ico"/>
    <resources location="/robots.txt" mapping="/robots.txt"/>
    
    <interceptors>
        <!-- 모바일 구분 -->
        <interceptor>
            <mapping path="/**"/>
            <exclude-mapping path="/resources/**" />
            <beans:bean class="org.springframework.mobile.device.DeviceResolverHandlerInterceptor"/>
        </interceptor>
    </interceptors>
    
    <!-- 스케줄러설정 -->
    <task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
    <task:executor id="myExecutor" pool-size="5"/>
    <task:scheduler id="myScheduler" pool-size="10"/>
</beans:beans>

상단의 xmlns 부분은 공통화 부분임으로 필요하신 부분만 넣으시면 됩니다만 일반적으로 위와 같이 하시면 spring의 대부분을 설정 할 수 있습니다. 중요설정부분 으로 task 옵션이 들어가는 부분을 참고하시면 되겠습니다. 특히나 component-scan 부분은 자신에 맞게 꼭 바꾸셔야 됩니다.


코드내용

package kr.jnu;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Schedul {

    /*
     * 5초 마다 실행
     */
    @Scheduled(fixedDelay=5000)
    public void init() {
        System.out.println("init");
    }

    /**
     * 매일 22시에 수행
     */    
    @Scheduled(cron="0 00 22 * * ?")
    public void download() {
        System.out.println("download");
    }
}


- @Scheduled 어노테이션 설정 예시 값


 cron

 리눅스의 CronTab 과 동일한 속성으로 주기를 설정

 fixedDelay

 최종 종료시간으로부터 지정된 millisecond 이후 수행
 ※ 지난프로세스가 종료된 이후

 fixedRate

 이전 시작시간으로부터 지정된 millisecond 이후 수행
 ※ 지난프로세스가 종료 되지 않아도 시작된 시간으로 부터



- cron 설정 예시 값


구분

시간

요일

범위

0 ~ 59

0 ~ 59

0 ~ 23

1 ~ 31

1 ~ 12

JAN ~ DEC

1(일) ~ 7(토)

SUN ~ SAT

 특수문자

, - * /

, - * / ? L W

 , - * /

, - * / ? L #

 비고

      



- 특수(복합)문자 사용 표


 값

 설명

*

 전체 범위

?

 지정된 값 없음

-

 지정 범위

,

 복수 값

/

 시작/간격

L

 해당 범위의 마지막 값

W

 가장 가까운 평일

LW

 마지막 값과 시작값

#

 요일/주차


Spring 5에서 실행결과 년도 부분은 에러가 발생하여 제외 하였습니다 ^^ 그리고 위버전은 3.X까지 크게 설정이 다르지 않는 것으로 보입니다.


※ Spring 스케줄러 task 설정 원문 링크

https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html


블로그 이미지

촌놈 개발자 일기

개발자로서 살아가는 느낌과 정보를 공유 합니다

,