Java의 ScheduledExecutorService를 이용해서 스케줄러를 만들어보자

2018. 5. 23. 22:52· Java

ScheduledExecutorService는 concurrent 패키지에 포함되어 있으며, '일정 시간 후' 또는 '주기적'으로 command(작업)를 실행시켜 줄 수 있는 녀석이다.

스프링을 사용했다면 간편하게 @Scheduled를 사용했겠지만, 쌩 자바를 쓸 일이 있어서 ScheduledExecutorService를 사용해봤다.

 

코드 자체가 직관적이기 때문에 거두절미하고 코드를 보자.

import java.time.Duration;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import static java.time.LocalDateTime.now;
import static java.util.concurrent.TimeUnit.SECONDS;

public class Scheduler {

    public static final String SEOUL_ZONE = "Asia/Seoul";
    public static final int ONE_DAY = 1;
    public static final int ONE_DAY_AS_SECOND = 24 * 60 * 60;
    public static final int SINGLE_POOL_SIZE = 1;

    private final ScheduledExecutorService scheduler;

    public Scheduler() {
        this.scheduler = Executors.newScheduledThreadPool(SINGLE_POOL_SIZE);
    }

    public void execute(Runnable command, int hour, int minute, int second) {
        ZonedDateTime now = ZonedDateTime.of(now(), ZoneId.of(SEOUL_ZONE));
        ZonedDateTime nextExecutionTime = this.getNextExecutionTime(hour, minute, second, now);
        scheduler.scheduleAtFixedRate(command, this.getInitialExecutionTime(now, nextExecutionTime), ONE_DAY_AS_SECOND, SECONDS);
    }

    private ZonedDateTime getNextExecutionTime(int hour, int minute, int second, ZonedDateTime now) {
        ZonedDateTime nextExecutionTime;
        nextExecutionTime = now
                        .withHour(hour)
                        .withMinute(minute)
                        .withSecond(second);

        if (this.isOverDay(now, nextExecutionTime))
            nextExecutionTime = nextExecutionTime.plusDays(ONE_DAY);

        return nextExecutionTime;
    }

    private boolean isOverDay(ZonedDateTime zonedNow, ZonedDateTime nextExecutionTime) {
        return zonedNow.compareTo(nextExecutionTime) > 0;
    }

    private long getInitialExecutionTime(ZonedDateTime now, ZonedDateTime nextExecutionTime) {
        Duration duration = Duration.between(now, nextExecutionTime);
        return duration.getSeconds();
    }

}
  1. 생성자에서 초기화를 해준다.
  2. 현재 시간과 실행 시간을 구한다.
  3. getInitialExecutionTime()을 통해서 두 시간의 차이를 구한다. => 지금부터 실행 시간까지 남은 시간
  4. scheduleAtFixedRate()에 위에서 얻은 결과를 토대로 호출한다.
execute(() -> System.out.println("Hello World"), 7, 0, 0);

위와 같이 호출하게 되면 7시마다 Hello World를 출력하게 된다.

 

참고

 

How to run certain task every day at a particular time using ScheduledExecutorService?

I am trying to run a certain task everyday at 5 AM in the morning. So I decided to use ScheduledExecutorService for this but so far I have seen examples which shows how to run task every few minute...

stackoverflow.com

 

저작자표시 비영리 변경금지 (새창열림)

'Java' 카테고리의 다른 글

lombok.config 옵션  (0) 2023.03.05
BigDecimal의 toString(), toPlainString(), toEngineeringString()  (0) 2018.09.11
[Jackson] JsonInclude 속성에 대해 알아보자.  (2) 2018.05.23
Java로 날씨 알림 서비스를 만들어보자 (OOP, Clean Code)  (1) 2018.05.21
Java의 List를 상황에 맞게 생성해보자 ( asList(), emptyList(), singletonList() )  (2) 2018.05.15
'Java' 카테고리의 다른 글
  • lombok.config 옵션
  • BigDecimal의 toString(), toPlainString(), toEngineeringString()
  • [Jackson] JsonInclude 속성에 대해 알아보자.
  • Java로 날씨 알림 서비스를 만들어보자 (OOP, Clean Code)
AlwaysPr
AlwaysPr
AlwaysPr
민수's 기술 블로그
AlwaysPr
전체
오늘
어제
  • All (38)
    • Programming (8)
    • Java (10)
    • Spring (13)
    • JavaScript (1)
    • Book (1)
    • Seminar (1)
    • Diary (4)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • record pattern
  • Java21
  • 가상스레드
  • loom project
  • @EnableBatchProcessing
  • DefaultBatchConfiguration
  • 레코드매칭
  • stringtemplates
  • 스프링배치5
  • structured-concurrency
  • 개발자
  • Spring
  • lombok.config
  • aop
  • Reactor
  • @Cachable
  • Spring batch5
  • virtual thread
  • 웹플럭스
  • java17
  • 고졸개발자
  • r2dbc
  • JobBuilder
  • scopedValue
  • Webflux
  • nonblocking
  • FFM
  • 자바21
  • StepBuilder
  • eventdriven

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.0
AlwaysPr
Java의 ScheduledExecutorService를 이용해서 스케줄러를 만들어보자
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.