티스토리 뷰

2016/09/07 - [개발/JAVA] - 스프링 부트(Spring boot)로 개발하기


위에서 기본적인 부트 환경이 세팅 되었으니 간단한 스케줄링 프로그램을 만들어보도록 한다.

매초마다 로깅을 하거나 배치처럼 작동할 수 있는 예제를 작성해본다.

스케줄링 설정
Application에 @EnableScheduling어노테이션을 달아준다.
package net.donnert.spring.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class Application {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}

Timer 소스 작성
package net.donnert.spring.boot;

import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Component
public class Timer {
	Logger logger = LoggerFactory.getLogger(this.getClass());
	private AtomicInteger loopCounter = new AtomicInteger();
	
	@Autowired
	private StopWatch watch;
	
	@PostConstruct
	public void init() {
		watch.start();
	}

	@Scheduled(fixedDelayString = "1000")
	public void tick() throws InterruptedException{
		watch.stop();
		logger.info(watch.prettyPrint());
		String taskName = "task-";
		taskName = taskName + String.valueOf(loopCounter.getAndIncrement());
		watch.start(taskName);
	}

	@Bean
	public StopWatch watch() {
		return new StopWatch();
	}
}
@Scheduled어노테이션을 통해 작업이 끝난 후 1초 후 다시 작업을 시작한다.
fixedRateString의 경우 이전 작업이 끝나지 않아도 1초마다 작업을 시작한다.


타이머 돌리면서 카운트 올리는게 끝이다.

작업 결과는 다음과 같다.  각각의 작업이 정확히(?) 1초 후 다시 시작되는걸 볼 수 있다.

2016-09-07 16:03:56.843  INFO 10640 --- [pool-1-thread-1] net.donnert.spring.boot.Timer            : StopWatch '': running time (millis) = 9188

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

ms     %     Task name

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

00178  002%  

01000  011%  task-0

01002  011%  task-1

01001  011%  task-2

01001  011%  task-3

01001  011%  task-4

01002  011%  task-5

01001  011%  task-6

01001  011%  task-7

01001  011%  task-8


마무리

@Scheduled의 cron속성으로 크론탭처럼(* * * * *) 설정도 가능하다.

야밤에 배치를 돌리거나 간단한 작업을 할 수 있는 프로그램이 끝났다.

심지어 우리는 logback 설정도 안했는데 쓰고있다.

이게 스프링 부트의 매력이다.


다음장으로 이어집니다

2016/09/08 - [개발/JAVA] - 스프링 부트(Spring boot)에서 프로퍼티 사용하기


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함