How to turn off Java timer

To stop the execution of a Java Timer, you can call the cancel() method of the Timer. Here is a simple example:

import java.util.Timer;
import java.util.TimerTask;

public class TimerExample {
    public static void main(String[] args) {
        Timer timer = new Timer();
        
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Hello, Timer!");
            }
        };
        
        // 启动计时器并执行任务
        timer.schedule(task, 1000, 1000);
        
        // 等待一段时间后关闭计时器
        try {
            Thread.sleep(5000);
            timer.cancel();
            System.out.println("Timer has been cancelled.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

In the example above, we created a Timer object and scheduled a TimerTask to perform a task using the schedule() method. We then called the cancel() method after waiting for 5 seconds to stop the execution of the timer.

bannerAds