> Java > java지도 시간 > 본문

자바의 타이머

PHPz
풀어 주다: 2024-08-30 15:53:07
원래의
356명이 탐색했습니다.

Java의 타이머는 Java에서 사용할 수 있습니다. util 패키지는 객체 클래스를 확장하고 직렬화 가능 및 복제 가능 인터페이스를 구현합니다. 타이머 클래스에는 타이밍 관련 활동을 수행하는 데 사용되는 메서드가 포함되어 있습니다. Java의 타이머 클래스는 시간 관련 작업 스케줄링을 수행하는 데 사용됩니다. Java 스레드는 Timer 클래스의 메서드를 사용하여 일정 시간이 지난 후 코드 섹션을 실행하거나 미리 정의된 일정 시간이 지난 후 코드를 반복적으로 실행하는 등의 작업을 예약합니다. 각 Timer 개체는 스레드와 관련된 모든 작업을 실행하는 별도의 백그라운드 실행 스레드에 바인딩됩니다. Java의 타이머 클래스는 스레드로부터 안전합니다. 즉, 한 번에 하나의 스레드만 Timer 클래스 메서드를 실행할 수 있습니다. 또한 Timer 클래스는 작업을 저장하기 위한 기본 데이터 구조로 바이너리 힙을 사용합니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

Java의 타이머 구문

다음은 Java에서 Timer 클래스를 사용하는 방법에 대한 기본 구문입니다.

구문:

// create a class extending TimerTask
class TimerHelper extends TimerTask
{
//define run method
public void run()
{
// Write Code to be executed by Timer
}
}
class MainClass{
public static void main(String[] args)
{
//create timer instance
Timer timer = new Timer();
// create Timer class instance
TimerTask task = new TimerHelper ();
// call timer method
timer.schedule(task, 3000,6000);
//first argument is timer object
// second argument is time in milliseconds after which the code will be first executed
// Third argument is time in milliseconds after which the code will be executed regularly.
}
}
로그인 후 복사

위 구문 설명: 구문은 Java에서 Timer 클래스가 사용되는 방식을 보여줍니다. 타이머 클래스를 사용하려면 TimerTask를 확장하는 클래스를 만들고 그 안에 run 메서드를 정의해야 합니다. run 메소드에는 시간에 따라 실행되어야 하는 로직이 포함되어 있습니다. 다음은 Timer 클래스 선언입니다.

public  class Timer extends Object
implements Serializable, Cloneable
로그인 후 복사

Java의 Timer 클래스 메서드

이제 Java Timer 클래스에서 사용할 수 있는 다양한 메소드와 필드가 무엇인지 살펴보겠습니다. Timer 클래스에서 일반적으로 사용되는 메소드 목록은 다음과 같습니다.

Method Name Description
public void schedule(TimerTask task, Date date) Schedules a task to be executed on the defined date.
public  void schedule (TimerTask task, Date firstTime, long timeperiod) The first argument is TimerTask to be executed; the second argument is the time after which the task is executed for the first time, and the third argument is seconds in milliseconds after which task will be executed regularly.
public  int purge() Used for removing all canceled tasks from the timer’s queue.
public void cancel() Cancel’s the timer.
public void schedule(TimeTask task, long delay) Schedules the task to be executed after the specified time in milliseconds.
public void schedule(TimeTask task, long delay, long period) The first argument is TimerTask to be executed; the second argument is the time in milliseconds after which task is executed for the first time, and the third argument is seconds in milliseconds after which task will be executed regularly.
public  void scheduleAtFixedRate(TimerTask task, Date firstTime, long timeperiod) The first argument is TimerTask to be executed; the second argument is the time after which the task is executed for the first time, and the third argument is seconds in milliseconds after which the task will be executed regularly.
public void scheduleAtFixedRate (TimeTask task, long delay, long period) The first argument is TimerTask to be executed; the second argument is the time in milliseconds after which task is executed for the first time, and the third argument is seconds in milliseconds after which task will be executed regularly.
메서드 이름 설명 공개 무효 일정(TimerTask 작업, 날짜 날짜) 정의된 날짜에 작업이 실행되도록 예약합니다. 공개  무효 일정(TimerTask 작업, 날짜 최초 시간, 긴 기간) 첫 번째 인수는 실행할 TimerTask입니다. 두 번째 인수는 작업이 처음으로 실행된 후의 시간이고, 세 번째 인수는 이후 작업이 정기적으로 실행되는 초(밀리초)입니다. 공개  int purge() 타이머 대기열에서 취소된 모든 작업을 제거하는 데 사용됩니다. 공개 무효 취소() 타이머를 취소하세요. 공개 무효 일정(TimeTask 작업, 긴 지연) 지정된 시간(밀리초) 후에 작업이 실행되도록 예약합니다. 공개 무효 일정(TimeTask 작업, 장기 지연, 장기) 첫 번째 인수는 실행할 TimerTask입니다. 두 번째 인수는 작업이 처음으로 실행된 후의 시간(밀리초)이고, 세 번째 인수는 작업이 정기적으로 실행된 후의 시간(밀리초)입니다. public  void ScheduleAtFixedRate(TimerTask 작업, 날짜 firstTime, 긴 기간) 첫 번째 인수는 실행할 TimerTask입니다. 두 번째 인수는 작업이 처음으로 실행된 후의 시간이고, 세 번째 인수는 작업이 정기적으로 실행된 이후의 초(밀리초)입니다. public void ScheduleAtFixedRate(TimeTask 작업, 장기 지연, 장기) 첫 번째 인수는 실행할 TimerTask입니다. 두 번째 인수는 작업이 처음으로 실행된 후의 시간(밀리초)이고, 세 번째 인수는 작업이 정기적으로 실행된 후의 시간(밀리초)입니다.

From the above-stated methods, we have found two methods that are similar in working but different in the name; they are schedule and scheduleAtFixedRate. The difference between the two is that in the case of fixed-rate execution, each execution is scheduled in accordance with the initial execution. If there is a delay in execution, then two or more executions will occur in quick succession to overcome the delay.

Constructors in Timer Class

The timer class contains four constructors for instantiating timer object.

  • Timer(): Creates a new Timer Object.
  • Timer(boolean isDaemon): Creates a timer object with a corresponding thread specified to run as a daemon.
  • Timer(String name): Creates a timer object with a corresponding thread name.
  • Timer(String name, boolean isDaemon): This method is a combination of the above two constructors.

One of the above four listed constructors can be called depending on our requirements.

Examples of Implementing Timer in Java

Below is the example of Timer in Java:

Example #1

To start things, let us see a basic example of Timer class. In this example, we will demonstrate the use of the schedule method of the Timer class.

Code:

package com.edubca.timer;
import java.util.Timer;
import java.util.TimerTask;
class TimerHelper extends TimerTask
{
public static int counter = 0;
public void run()
{
counter++;
System.out.println("Timer run Number " + counter);
}
}
public class Main
{
public static void main(String[] args)
{
Timer timer = new Timer();
TimerTask timerhelper = new TimerHelper();
timer.schedule(timerhelper, 3000, 2000);
}
}
로그인 후 복사

Explanation of the above code: The above code will execute the run method for the first time after 3 seconds as the first argument is 3000, and after every 2 seconds, the run method will be executed regularly. Here is the output that will be displayed:

Output:

자바의 타이머

Example #2

In this example, we will see how to terminate a timer thread after a given number of timer runs.

Code:

package com.edubca.timer;
import java.util.Timer;
import java.util.TimerTask;
class TimerHelper extends TimerTask
{
public static int counter = 0;
public void run()
{
counter++;
if(counter ==3){
this.cancel();
System.out.println("Now Cancelling Thread!!!!!");
return;
}
System.out.println("Timer run Number " + counter);
}
}
public class Demo
{
public static void main(String[] args)
{
Timer timer = new Timer();
TimerTask helper = new TimerHelper();
helper.schedule(task, 3000, 2000);
}
}
로그인 후 복사

In the above example, the timer will cancel after the three times run method is called using the timer class’s cancel method.

Output:

자바의 타이머

위 내용은 자바의 타이머의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!