Java 타이머, TimerTask, 예제가 있는 알림 클래스 자습서
게시 됨: 2021-02-04
java.util.Timer
는 미래의 특정 시간에 스레드가 실행되도록 예약하는 데 사용할 수 있는 유틸리티 클래스입니다. Java Timer 클래스를 사용하여 작업을 한 번만 실행하거나 정기적으로 실행하도록 예약할 수 있습니다.
java.util.TimerTask
는 Runnable 인터페이스를 구현하는 추상 클래스이며 Java Timer 클래스를 사용하여 예약할 수 있는 자체 TimerTask를 생성하려면 이 클래스를 확장해야 합니다.
Timer 클래스는 스레드로부터 안전하며 여러 스레드가 외부 동기화 없이 단일 Timer 개체를 공유할 수 있습니다. 타이머 클래스는 java.util.TaskQueue를 사용하여 주어진 규칙적인 간격으로 작업을 추가하고 언제든지 TimerTask를 실행하는 스레드는 하나만 있을 수 있습니다. 예를 들어 10초마다 실행하도록 타이머를 생성하지만 단일 스레드 실행에는 20초가 걸리는 경우 그러면 Timer 개체는 대기열에 작업을 계속 추가하고 한 스레드가 완료되자마자 대기열에 알리고 다른 스레드가 실행을 시작합니다.

Timer 클래스는 Object wait 및 notify 메소드를 사용하여 작업을 예약합니다. TimerTask는 abstract class
이며 구체적인 구현을 제공하기 위해 상속합니다. TimerTask 클래스는 Runnable
interface
를 implements
하므로 스레드이므로 TimerTask 구현도 스레드입니다.
매우 간단한 Timer 및 TimerTask 예제: 5 seconds
작업이 실행됩니다.
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 |
package com . crunchify . tutorials ; import java . util . Timer ; import java . util . TimerTask ; /** * Author: Crunchify.com */ public class CrunchifyTimerTaskExample { Timer timer ; public CrunchifyTimerTaskExample ( int seconds ) { timer = new Timer ( ) ; timer . schedule ( new CrunchifyReminder ( ) , seconds * 1000 ) ; } class CrunchifyReminder extends TimerTask { public void run ( ) { System . out . format ( "Timer Task Finished..!%n" ) ; timer . cancel ( ) ; // Terminate the timer thread } } public static void main ( String args [ ] ) { new CrunchifyTimerTaskExample ( 5 ) ; System . out . format ( "Task scheduled.. Now wait for 5 sec to see next message..%n" ) ; } } |
결과:
1 2 |
Task scheduled . . Now wait for 5 sec to see next message . . Time ' s up ! |
이 간단한 프로그램은 타이머 스레드가 실행할 작업을 구현하고 예약하는 다음 기본 부분을 보여줍니다.
-
TimerTask
의 사용자 지정 하위 클래스를 구현합니다.run
메서드에는 작업을 수행하는 코드가 포함되어 있습니다. 이 예에서 하위 클래스의 이름은 CrunchifyReminder입니다. -
Timer
클래스를 인스턴스화하여 스레드를 만듭니다. -
TimerTask
객체를 인스턴스화합니다(new CrunchifyReminder()
). - 실행을 위해 타이머 작업을 예약합니다.
어떻게 이 TimerTask를 반복적으로 수행할 수 있습니까?
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
package crunchify . com . tutorials ; import java . util . Timer ; import java . util . TimerTask ; import java . awt . Toolkit ; /** * Author: Crunchify.com * Java Timer and TimerTask - Reminder Class Tutorials */ public class CrunchifyTimerTaskExample { // Toolkit This class is the abstract superclass of all actual implementations of the Abstract Window Toolkit. // Subclasses of the Toolkit class are used to bind the various components to particular native toolkit implementations. Toolkit toolkit ; // Timer A facility for threads to schedule tasks for future execution in a background thread. // Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals. Timer timer ; public CrunchifyTimerTaskExample ( ) { toolkit = Toolkit . getDefaultToolkit ( ) ; timer = new Timer ( ) ; // schedule() Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. // Subsequent executions take place at approximately regular intervals separated by the specified period. timer . schedule ( new CrunchifyReminder ( ) , 0 , // initial delay 1 * 1000 ) ; // subsequent rate } // TimerTask A task that can be scheduled for one-time or repeated execution by a Timer. // A timer task is not reusable. Once a task has been scheduled for execution on a Timer or cancelled, // subsequent attempts to schedule it for execution will throw IllegalStateException. class CrunchifyReminder extends TimerTask { int loop = 5 ; public void run ( ) { if ( loop > 0 ) { // beep() Emits an audio beep depending on native system settings and hardware capabilities. toolkit . beep ( ) ; System . out . format ( "Knock Knock..!\n" ) ; loop -- ; } else { toolkit . beep ( ) ; System . out . format ( "\nThat's it.. Done..!" ) ; // cancel() Terminates this timer, discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists). Once a timer has been terminated, // its execution thread terminates gracefully, and no more tasks may be scheduled on it. timer . cancel ( ) ; } } } public static void main ( String args [ ] ) { new CrunchifyTimerTaskExample ( ) ; System . out . format ( "Task scheduled..!%n \n" ) ; } } |
결과:
1 2 3 4 5 6 7 8 9 |
Task scheduled . . ! Knock Knock . . ! Knock Knock . . ! Knock Knock . . ! Knock Knock . . ! Knock Knock . . ! That ' s it . . Done . . ! |
기본적으로 프로그램은 타이머 스레드가 실행되는 동안 계속 실행됩니다. 다음 네 가지 방법으로 타이머 스레드를 종료할 수 있습니다.

- 타이머에서
cancel
를 호출합니다. 타이머 작업의run
방법과 같이 프로그램의 어느 곳에서나 이 작업을 수행할 수 있습니다. -
new Timer(true)
와 같이 타이머를 생성하여 타이머의 스레드를 "데몬"으로 만듭니다. 프로그램에 남은 스레드가 데몬 스레드뿐이면 프로그램이 종료됩니다. - 모든 타이머의 예약된 작업 실행이 완료되면
Timer
개체에 대한 모든 참조를 제거합니다. 결국 타이머의 스레드가 종료됩니다. - 전체 프로그램(및 모든 해당 스레드)을 종료하는
System.exit
메서드를 호출합니다.