Make a Countdown Timer in Java

Rupam Yadav Jun 03, 2021
  1. Countdown Timer in Java Using ScheduledExecutorService
  2. Countdown Timer in Java Using Timer and TimerTask
Make a Countdown Timer in Java

Today, we’ll demonstrate how you can make a countdown timer in Java using two methods without relying on any third-party library. We can either use the timer in a GUI window or the console just to test it. Check out the codes we have below!

Countdown Timer in Java Using ScheduledExecutorService

In this first method, we use the ExecutorService interface to call its method newScheduledThreadPool(), which creates a thread pool that uses the same fixed number of assigned threads. In the newScheduledThreadPool() method, we pass the number of threads that we want in the pool. In this case, we want only one thread to run the timer.

The Executors.newScheduledThreadPool() function returns a ScheduledExecutorService object that we named scheduler. Next, we override the run() method from the Runnable interface. A Runnable instance is used to execute the thread. In Runnable, we create a variable countdownStarter and initialize it with the number in seconds from where we want to start the countdown timer.

Now inside the run() method, we print countdownStarter, and decrease its value by one. To stop the timer when it reaches zero, we create a condition to check the countdownStarter value. If its value becomes less than zero, it prints a message and shuts down the scheduler, which is the Executor Service using the scheduler.shutdown() command.

At last, we use the scheduler object to call the scheduleAtFixedRate() method that runs the given action periodically and takes four arguments. The first argument is the runnable instance; the second is the time delay on the first execution; the third is the delay between actions. Here, we gave the delay as one that should be equal to one second, as the fourth argument suggests.

import java.util.concurrent.*;

import static java.util.concurrent.TimeUnit.SECONDS;

public class Countdown {
    public static void main(String[] args) {

        final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        final Runnable runnable = new Runnable() {
            int countdownStarter = 20;

            public void run() {

                System.out.println(countdownStarter);
                countdownStarter--;

                if (countdownStarter < 0) {
                    System.out.println("Timer Over!");
                    scheduler.shutdown();
                }
            }
        };
        scheduler.scheduleAtFixedRate(runnable, 0, 1, SECONDS);
    }
}

Output:

20
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
Timer Over!

Countdown Timer in Java Using Timer and TimerTask

In this example, we use two classes, Timer and TimerTask, that come with the java.util package. Both the classes are used to schedule tasks for execution in the background thread. For this example, we use the jFrame object to show the timer in a GUI window. First, we create a jFrame object, then a jLabel that shows the text of the timer. We set the frame’s layout as FlowLayout() and set the position and size of the window.

Next, we add the jLabel to the frame. To create the countdown timer, we create a Timer object and call its method scheduleAtFixedRate(), which schedules and repeats the specified task at a fixed rate, as the name suggests.

Now, as the scheduleAtFixedRate() mate takes a TimerTask object as its first argument, we create an object using new TimerTask(). For the second and third arguments, they schedule the task to execute and the period in milliseconds between each execution.

For the next step, we need to create a variable and initialize it with the number that we want to start the countdown with. Then, we call the run() method and set the text of the jLabel component as i. To stop the timer, we call timer.cancel().

import javax.swing.*;
import java.awt.*;
import java.util.Timer;
import java.util.TimerTask;

public class Countdown {
    public static void main(String[] args) {

        JFrame jframe = new JFrame();
        JLabel jLabel = new JLabel();
        jframe.setLayout(new FlowLayout());
        jframe.setBounds(500, 300, 400, 100);

        jframe.add(jLabel);
        jframe.setVisible(true);

        Timer timer = new Timer();

        timer.scheduleAtFixedRate(new TimerTask() {
            int i = 20;

            public void run() {

                jLabel.setText("Time left: " + i);
                i--;

                if (i < 0) {
                    timer.cancel();
                    jLabel.setText("Time Over");
                }
            }
        }, 0, 1000);
    }
}

Output:

java countdown timer

Author: Rupam Yadav
Rupam Yadav avatar Rupam Yadav avatar

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

LinkedIn

Related Article - Java Timer