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 TestsStart 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
Constructors
Countdown Timer has a constructor, as depicted below.
CountDownTimer (long millisInFuture, long CountDownInterval)
Different methods are mentioned below:
public final void cancel ()
Definition: This method helps in canceling the count down.
public final void onFinish ()
Definition: This method helps in callbacking when the time is up.
public abstract void onTick ()
Definition: This method helps in callbacking during regular intervals.
public final CountDownTimer start()
Definition: This method helps in starting the countdown.
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;
5. Set an instance of timer.
timer = new Timer(cntdwn, this);
6. Start the timer using the start() method.
timer.start();
7. Save the Java file you have created.
8. Compile the code and press Run.
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.
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!!! "); } }
Output:
On executing the code, the following message will be displayed.
Once the countdown timer stops, a message will be displayed below, indicating that the time is set as the countdown is over.
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; } }
Output:
In this program, the user will be asked to input the seconds for counting down.
After entering the seconds, we will be able to see the countdown is getting displayed.
We can see that 3,2,1,0 gets displayed after each second.
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. . ."); } }
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.
After the successful execution, a message “The Time’s over” gets printed, indicating that the countdown timer is up.
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!