타이머: Timer, ScheduledExcutorService :: 행복한 프로그래머

posted by 쁘로그램어 2018. 6. 19. 17:49

java.util.Timer 클래스는 백그라운드에서 특정한 시간 또는 일정 시간을 주기로 반복적으로 특정 작업을 실행할 수 있도록 해 준다. TimerTask 는 아래와 같은 기능을 추가해준다.

* 태스크를 시작할때와 취소할때를 통제할수있게함.

* 처음 시작할때 타이밍을 원하는데로 할수있음.


# PrintTimer.java

public class PrintTimer {

   

   public static void main(String[] args) {

      ScheduledJob job = new ScheduledJob();

      Timer jobScheduler = new Timer();

      jobScheduler.scheduleAtFixedRate(job, 0, 3000);

      try {

         Thread.sleep(20000);

      } catch(InterruptedException ex) {

         //

      }

      jobScheduler.cancel();

   }

}

class ScheduledJob extends TimerTask {

   

   public void run() {

      System.out.println(new Date());

   }

}


자바 스레드를 특정 주기마다 수행하고 싶은 경우 ScheduledExcutorService를 사용하는 것이 좋다.

Java SE5 의  java.util.concurrent 에서 소개된 유틸이며 아래와 같은 특징이 있다.

* Timer 들의 싱글쓰레드와 비교하여 쓰레드풀로서 실행된다.

* 처음 실행시 딜레이를 제공하며 매우 유연하다.

* 타임 인터벌을 제공하기위해  멋진 conventions 을 제공한다.

* 보다 정확한 타임 인터벌 의 태스크 수행 


# ScheduleExecutorServiceEx.java

import java.util.Date;

import java.util.concurrent.Executors;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.TimeUnit;


public class ScheduleExecutorServiceEx {

    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);


    public static void main(String[] args) {

        ScheduleExecutorServiceEx se = new ScheduleExecutorServiceEx();

        se.timerInit();


        try{

            Thread.sleep(20000);

            timerStop();

        }catch (Exception e){

            e.printStackTrace();

        }

    }


    public static void timerInit() {

        System.out.println("timerInit");

        timerStart(1, 1);

        timerStart(2, 5);

        timerStart(3, 10);

    }


    public static void timerStart(final int condition, int time) {

        final Runnable runnable = new Runnable() {

            @Override

            public void run() {

                switch (condition){

                    case 1:{

                        System.out.println("A==========="+new Date());

                        break;

                    }

                    case 2:{

                        System.out.println("=====B======"+new Date());

                        break;

                    }

                    case 3:{

                        System.out.println("===========C"+new Date());

                        break;

                    }

                }

            }

        };

        scheduler.scheduleAtFixedRate(runnable, 1, time, TimeUnit.SECONDS);

    }


    public static void timerStop() {

        System.out.println("=========================");

        System.out.println("isShutdown :"+scheduler.isShutdown());

        System.out.println("isTerminated :"+scheduler.isTerminated());

        System.out.println("=========================");


        scheduler.shutdownNow();


        System.out.println("=========================");

        System.out.println("isShutdown :"+scheduler.isShutdown());

        System.out.println("isTerminated :"+scheduler.isTerminated());

        System.out.println("=========================");


        try{

            System.out.println(scheduler.awaitTermination(2,TimeUnit.SECONDS));

        }catch (Exception e){

            e.printStackTrace();

        }

    }

}


※ 참고 사이트 ※

http://javacan.tistory.com/entry/29

http://hamait.tistory.com/211

http://soulduse.tistory.com/9

http://unikys.tistory.com/181

http://promobile.tistory.com/105

http://jeong-pro.tistory.com/150

'Java > Java' 카테고리의 다른 글

SimpleDateFormat: 현재날짜 구하기  (0) 2018.06.19
GSON – How to parse input JSON with dynamic keys  (0) 2018.05.28
Map Collection이란?  (0) 2018.05.23
Set Collection이란?  (0) 2018.05.23
List Collection이란?  (0) 2018.05.23