Home > Java > javaTutorial > Java Countdown Timer

Java Countdown Timer

王林
Release: 2024-08-30 15:53:13
Original
1066 people have browsed it

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
Copy after login

Constructors

Countdown Timer has a constructor, as depicted below.

CountDownTimer (long millisInFuture, long CountDownInterval)
Copy after login
  • 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 ()
Copy after login

Definition: This method helps in canceling the count down.

2. OnFinish

public final void onFinish ()
Copy after login

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

3. onTick

public abstract void onTick ()
Copy after login

Definition: This method helps in callbacking during regular intervals.

4. start

public final CountDownTimer start()
Copy after login

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;
Copy after login

5. Set an instance of timer.

timer = new Timer(cntdwn, this);
Copy after login

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

timer.start();
Copy after login

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!!! ");
}
}
Copy after login

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;
}
}
Copy after login

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. . .");
}
}
Copy after login

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

Conclusion

In Java, time-sensitive tasks are performed using Countdown timers. Most of these tasks are exams, games, notifications, etc. A detailed note on the Countdown timer is discussed in this document in detail.

The above is the detailed content of Java Countdown Timer. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template