본문 바로가기
programming/SpringJava

자바 스프링 스케줄러 구현과 실행 cron 표현식 사용

by 개코 - 개발과 코딩 2021. 3. 31.

프로그램을 통해 반복적인 일을 위해 스케줄러를 만든다. 자바 스프링에서는 cron 표현식을 사용하여 스케줄러를 만들 수 있다. cron 표현식을 반복적인 시간표현을 말한다. 스프링 스케줄러를 구현하고 실행해 본다.

스케줄러 구현하기

  1. servlet-context.xml 파일에 스케줄러 환경설정하기
  2. 스케줄러 구현하기
  3. 실행화면 동작확인하기

servlet-context.xml 파일에 스케줄러 환경설정하기

먼저, servlet-context.xml 에 job scheduler 관련한 환경설정을 추가해야 한다.

아래의 코드는 job scheduler 를 servlet-context.xml 에 추가할 것이다.

xmlns:task="http://www.springframework.org/schema/task
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd

<!-- 스프링 스케줄러 -->
<task:scheduler id="jobScheduler" pool-size="10" />
<task:annotation-driven scheduler="jobScheduler" />

위의 추가할 코드를 아래의 전체적인 코드 servlet-context.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:task="http://www.springframework.org/schema/task"
                xsi:schemaLocation="http://www.springframework.org/schema/mvc
                	https://www.springframework.org/schema/mvc/spring-mvc.xsd
                    http://www.springframework.org/schema/beans
                    https://www.springframework.org/schema/beans/spring-beans.xsd
                    http://www.springframework.org/schema/context
                    https://www.springframework.org/schema/context/spring-context.xsd
                    http://www.springframework.org/schema/task
                    http://www.springframework.org/schema/task/spring-task.xsd">
	
    	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
    
    	<!-- Enables the Spring MVC @Controller programming model -->
    	<annotation-driven />
    
    	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    	<resources mapping="/resources/**" location="/resources/" />
    
    	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    	<beans:property name="prefix" value="/WEB-INF/views/" />
    	<beans:property name="suffix" value=".jsp" />
        
	</beans:bean>
    
    <!-- 스프링 스케줄러 -->
    <task:scheduler id="jobScheduler" pool-size="10" />
    <task:annotation-driven scheduler="jobScheduler" /> 
    
    <context:component-scan base-package="com.crd.test" />
    
</beans:beans>

스케줄러 구현하기

자바 @Component 클래스 파일을 만들고 @Scheduled 메서드를 추가하여 스케줄러를 위한 코드를 만든다.

이렇게 만들어 주면 아파치 서버가 실행되며 자동으로 등록이 된다.

package com.crd.test;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/** * Handles requests for the application home page. */
@Component
public class ScheduleController
{ 
	/*** 1초마다 실행 */
    @Scheduled(cron = "0/1 * * * * *")
    public void CronScheduler() { 
    	LocalDateTime vLocalDateTime = LocalDateTime.now();
        DateTimeFormatter vDateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
        System.out.println("Cron 스케줄러 : " + vLocalDateTime.format(vDateTimeFormatter));
	}
}

실행 화면 동작 확인하기

아파치 서버를 실행하고 위의 코드는 테스트를 위해 1초마다 자동으로 실행되는 것을 볼 수 있다. 이것만 할 수 있다면 자동으로 할 수 있는 유용한 것들이 많이 있다.

반응형

댓글