在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.

作者: dawei

【声明】:永州站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

为您推荐

联系我们

联系我们

0577-28828765

在线咨询: QQ交谈

邮箱: xwei067@foxmail.com

工作时间:周一至周五,9:00-17:30,节假日休息

返回顶部