加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

在Java中创建重复的定时器提醒

发布时间:2020-12-14 16:21:54 所属栏目:Java 来源:网络整理
导读:我想要一个类,每2秒更改自己的私有变量.我知道如果我做某事 import java.util.Timer;//...Timer timer;//...timer.schedule(new ChangeSomething(),2000); 它将在2秒后执行ChangeSomething(),有没有办法告诉它每2秒钟做一些事情,或者如果我放在ChangeSomethi
我想要一个类,每2秒更改自己的私有变量.我知道如果我做某事
import java.util.Timer;
//...
Timer timer;
//...
timer.schedule(new ChangeSomething(),2000);

它将在2秒后执行ChangeSomething(),有没有办法告诉它每2秒钟做一些事情,或者如果我放在ChangeSomething()

timer.schedule(new ChangeSomething(),2000);

它会工作吗

在旁注中,timer.cancel()究竟做了什么?

解决方法

使用timer.scheduleAtFixedRate()来安排它每两秒重复一次:

Schedules the specified task for repeated fixed-rate execution,beginning at the specified time. Subsequent executions take place at approximately regular intervals,separated by the specified period.

从用于Timer.cancel()的javadoc:

Terminates this timer,discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists). Once a timer has been terminated,its execution thread terminates gracefully,and no more tasks may be scheduled on it.

编辑:

关于执行一个任务一次的Timer的内部执行线程:

After the last live reference to a Timer object goes away and all outstanding tasks have completed execution,the timer’s task execution thread terminates gracefully (and becomes subject to garbage collection). However,this can take arbitrarily long to occur. By default,the task execution thread does not run as a daemon thread,so it is capable of keeping an application from terminating. If a caller wants to terminate a timer’s task execution thread rapidly,the caller should invoke the timer’s cancel method.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读