Heim > Java > javaLernprogramm > Java-Countdown-Timer

Java-Countdown-Timer

王林
Freigeben: 2024-08-30 15:53:13
Original
1072 Leute haben es durchsucht

In Java, there are several situations where time-sensitive tasks such as countdown timers are added to Java forms. In those timers, the amount of time until a function is triggered can be set by the user. It will be continually running in the case where the function has to be continuously triggered. When the count downtime is reached, the timer can be reset. In-built packages of Java can be used to set the amount of time and perform certain actions at regular intervals. All these can be changed based on the requirement of the user. This document lets us see how a countdown timer can be set in Java.

ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Declaration of CountDownTimer in Java

Following is the declaration of the countdown timer in Java.

public abstract class CountDownTimer extends Object
Nach dem Login kopieren

Constructors

Countdown Timer has a constructor, as depicted below.

CountDownTimer (long millisInFuture, long CountDownInterval)
Nach dem Login kopieren
  • millisInFuture: This parameter mentions the count of millis in the future from when the start() method is called until the onFinish() method is called.
  • countDownInterval: Interval to get onTick() callbacks.

Methods of Java Countdown Timer

Different methods are mentioned below:

1. cancel

public final void cancel ()
Nach dem Login kopieren

Definition: This method helps in canceling the count down.

2. OnFinish

public final void onFinish ()
Nach dem Login kopieren

Definition: This method helps in callbacking when the time is up.

3. onTick

public abstract void onTick ()
Nach dem Login kopieren

Definition: This method helps in callbacking during regular intervals.

4. start

public final CountDownTimer start()
Nach dem Login kopieren

Definition: This method helps in starting the countdown.

How Does Countdown Time Work in Java?

The following are the steps to perform the countdown timer in Java.

1. Open the IDE where you want to create a Java File. IDE can be Eclipse, Netbeans, or JBuilder X, depending on the user’s requirement.

2. Import the package. Import all the required time classes at your Java main file’s top.

3. Set the countdown time.

4. Countdown happens in milliseconds. So, make sure that variables are also in milliseconds. If you want to set the timer as 5 seconds, “5000” has to be mentioned, as shown below.

int cntdwn = 5000;
Nach dem Login kopieren

5. Set an instance of timer.

timer = new Timer(cntdwn, this);
Nach dem Login kopieren

6. Start the timer using the start() method.

timer.start();
Nach dem Login kopieren

7. Save the Java file you have created.

8. Compile the code and press Run.

Examples of Java Countdown Timer

There are certain ways in which a countdown timer can be set. Let us see how to implement them with the help of the Java programming language.

Example #1

Program to set the timer in Java

Code:

import java.util.Timer;
import java.util.TimerTask;
//sample class
public class CountDownTimerExample {
//declare timer t
Timer t;
//constructor of the class
public CountDownTimerExample(int seconds) {
t = new Timer();
//schedule the timer
t.schedule(new rt(), seconds*1000);
}
//sub class that extends TimerTask
class rt extends TimerTask {
//task to perform on executing the program
public void run() {
System.out.println("Seconds you have input is over..!!! ");
t.cancel(); //stop the thread of timer
}
}
//main method
public static void main(String args[]) {
//pass 5 seconds as timer
new CountDownTimerExample(5);
System.out.println("Count down starts now!!! ");
}
}
Nach dem Login kopieren

Output:

On executing the code, the following message will be displayed.

Java-Countdown-Timer

Once the countdown timer stops, a message will be displayed below, indicating that the time is set as the countdown is over.

Java-Countdown-Timer

Example #2

Another way to set a countdown timer in Java

Code:

//Java program to create a count down timer
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
//class
public class CountDownTimerExample {
//declare the interval i and timer t
static int i;
static Timer t;
//main method
public static void main(String[] args) {
//create object for scanner
Scanner <u>sc</u> = new Scanner(System.in);
// input the seconds you want to count down
System.out.print("Enter the seconds you want to count down : ");
//save the seconds that is input in to the variable <u>sec</u>
String sec = sc.nextLine();
//set delay and period as 1000
int del = 1000;
int per = 1000;
t = new Timer();
i = Integer.parseInt(sec);
System.out.println(sec);
//performs the <u>specifiedd</u> task at certain intervals
t.scheduleAtFixedRate(new TimerTask()
{
//task to be performed
public void run()
{
System.out.println(seti());
}
}, del, per);
}
//set interval
private static final int seti() {
//if interval is 1, cancel
if (i == 1)
t.cancel();
return --i;
}
}
Nach dem Login kopieren

Output:

In this program, the user will be asked to input the seconds for counting down.

Java-Countdown-Timer

After entering the seconds, we will be able to see the countdown is getting displayed.

Java-Countdown-Timer

We can see that 3,2,1,0 gets displayed after each second.

Example #3

Program to create a countdown timer that displays a message after each second.

Code:

import java.awt.Toolkit;
import java.util.Timer;
import java.util.TimerTask;
public class CountDownTimerExample {
//declare tk and t
Toolkit tk;
Timer t;
//constructor of CountDownTimerExample class
public CountDownTimerExample() {
tk = Toolkit.getDefaultToolkit();
t = new Timer();
//initial delay and subsequent rate
t.schedule(new rt(), 0, 1*1000);
}
class rt extends TimerTask {
//declare a variable beep
int beep = 3;
//task to be performed
public void run() {
//if BEEP VARIABLE IS GREATER THAN ZERO
if (beep > 0) {
//perform beep operation and print after each second
tk.beep();
System.out.println("One second over . . . Beep!");
//decrement the value beep
beep--;
}
//if beep variable is less than zero
else {
tk.beep();
System.out.println("The Time's over. . .!");
//AWT thread stops
System.exit(0);
}
}
}
public static void main(String args[]) {
System.out.println("Task is going to start. . .");
new CountDownTimerExample();
System.out.println("Task that is set up is scheduled. . .");
}
}
Nach dem Login kopieren

Output:

It can be seen that on executing the code, two messages get displayed, such as “Task is going to start. . .” and “Task that is set up is scheduled … ”. After that, count down gets the start.

Java-Countdown-Timer

After the successful execution, a message “The Time’s over” gets printed, indicating that the countdown timer is up.

Java-Countdown-Timer

Fazit

In Java werden zeitkritische Aufgaben mithilfe von Countdown-Timern ausgeführt. Bei den meisten dieser Aufgaben handelt es sich um Prüfungen, Spiele, Benachrichtigungen usw. Ein detaillierter Hinweis zum Countdown-Timer wird in diesem Dokument ausführlich besprochen.

Das obige ist der detaillierte Inhalt vonJava-Countdown-Timer. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Verwandte Etiketten:
Quelle:php
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage