gpt4 book ai didi

java - 如何做一个定时器监听器?

转载 作者:行者123 更新时间:2023-12-01 11:39:46 25 4
gpt4 key购买 nike

我是 Java 新手,我想编写一个程序,在检测到时间时执行确定的操作。

示例:我启动一个计时器,当 30 段过去时,显示一条消息,3 分钟过去后,执行另一个操作,等等。

我该怎么做?

谢谢

最佳答案

使用Timer类,你可以做这样的事情:

public void timer() {

TimerTask tasknew = new MyTask();
Timer timer = new Timer();

/* scheduling the task, the first argument is the task you will be
performing, the second is the delay, and the last is the period. */
timer.schedule(tasknew, 100, 100);
}

}

这是扩展 TimerTask 并执行某些操作的类的示例。

 class MyTask extends TimerTask {

@Override
public void run() {
System.out.println("Hello world from Timer task!");

}
}

如需进一步阅读,请查看

Timer Docs

Timer schedule example

关于java - 如何做一个定时器监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29634116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com