brunch

You can make anything
by writing

C.S.Lewis

by 서준수 Feb 17. 2019

ScheduledExecutorService

scheduleAtFixedRate vs. scheduleWithFixe

scheduleAtFixedRate vs. scheduleWithFixedDelay


scheduleAtFixedRate(command, initialDelay, period, unit)

  1) initialDelay 후에 period 간격으로 command 실행

  2) 어떤 이유(예 : garbage collection 또는 기타 백그라운드 활동)로 인해 실행이 지연되면 두 번 이상 실행될 수 있음

  ex) scheduleAtFixedRate(command, 1, 2, TimeUnit.SECONDS) 일 때

      실행시간이 12시00분00분이면 1초 후인 12시00분01초 command가 실행되고 다음은 12시00분3초, 5초, 7초 ~이다. command의 종료 여부와 관계가 없다. period 주기 정확히 반복한다.


scheduleWithFixedDelay(command, initialDelay, delay, unit)

  1) initialDelay 후에 delay 간격으로 command 실행

  2) command가 종료된 후를 기준으로 delay 간격으로 command 실행

  ex) scheduleWithFixedDelay(command, 1, 2, TimeUnit.SECONDS) 일 때

      실행시간이 12시00분00분이면 1초 후인 12시00분01초 command가 실행된다. 그 후 command가 10초 후 종료되었다면 다음은 12시00분13초이다. 왜냐하면 command가 소모한 10초의 시간 + delay 시간 2초를 포함한 것이다. 만약 이 다음에 command가 2초 후 종료되었다면 command가 소모한 2초의 시간 + delay 시간 2초로 총 4초 후인 12시00분17초에 다시 실행한다.



import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class dailyCode {
    public static void main(String[] args) {
        final int INTERRUPTER_NUM = 20;
        ScheduledExecutorService timer1 = Executors.newSingleThreadScheduledExecutor();
        ScheduledExecutorService timer2 = Executors.newSingleThreadScheduledExecutor();
        ScheduledExecutorService[] interrupter = new ScheduledExecutorService[INTERRUPTER_NUM];

        Date now = new Date();

        System.out.println("First TimeStamp : " + new SimpleDateFormat("MM-dd-yyyy / hh:mm:ss").format(now) + "\n");

        Runnable timeStamp1 = new Runnable() {
            @Override
            public void run() {
                Date now = new Date();
                System.out.println("TimeStamp1 : " + new SimpleDateFormat("MM-dd-yyyy / hh:mm:ss").format(now));
            }
        };

        Runnable timeStamp2 = new Runnable() {
            @Override
            public void run() {
                Date now = new Date();
                System.out.println("TimeStamp2 : " + new SimpleDateFormat("MM-dd-yyyy / hh:mm:ss").format(now)+ "\n");
            }
        };

        Runnable interrupt = new Runnable() {
            @Override
            public void run() {
                while(true){
                }
            }
        };

        for(int i=0; i<INTERRUPTER_NUM; i++){
            interrupter[i] = Executors.newSingleThreadScheduledExecutor();
            interrupter[i].execute(interrupt);
        }

        timer1.scheduleAtFixedRate(timeStamp1, 2, 10, TimeUnit.SECONDS);
        timer2.scheduleWithFixedDelay(timeStamp2, 2, 10, TimeUnit.SECONDS);
    }
}


매거진의 이전글 Callback using interface
작품 선택
키워드 선택 0 / 3 0
댓글여부
afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari