在Java中创建重复计时器提醒 [英] Creating a repeating timer reminder in Java

查看:54
本文介绍了在Java中创建重复计时器提醒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个每2秒更改一次自己的私有变量的类.我知道如果我做

I want to have a class that changes its own private variables every 2 seconds. I know that if I do something like

import java.util.Timer;
//...
Timer timer;
//...
timer.schedule(new ChangeSomething(), 2000);

它将在2秒后执行 ChangeSomething(),是否有办法告诉它每2秒执行一次操作,或者,如果我将其放入 ChangeSomething()

It will execute ChangeSomething() after 2 seconds, is there a way to tell it to do something every 2 seconds, or, If I put inside ChangeSomething()

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

能行吗?

在旁注中, timer.cancel()到底能做什么?

On a side-note, what does timer.cancel() exactly do?

推荐答案

使用 timer.scheduleAtFixedRate()将其安排为每两秒重复一次:

Use timer.scheduleAtFixedRate() to schedule it to recur every two seconds:

计划从指定的时间开始重复执行固定速率的指定任务.随后的执行大约每隔固定的时间间隔执行一次,并以指定的时间间隔分隔开.

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.

从Javadoc中获取 Timer.cancel():

From the javadoc for Timer.cancel():

终止此计时器,丢弃任何当前计划的任务.不干扰当前正在执行的任务(如果存在).计时器终止后,其执行线程将正常终止,并且无法在其上安排更多任务.

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 的内部执行线程有关:

Relating to internal execution thread for a Timer that executes a single task once:

在最后一个对Timer对象的实时引用消失并且所有未完成的任务均已完成执行之后,计时器的任务执行线程会正常终止(并受到垃圾回收的影响).但是,这可能需要花费很长时间才能发生.默认情况下,任务执行线程不会作为守护程序线程运行,因此它能够防止应用程序终止.如果调用方想快速终止计时器的任务执行线程,则调用方应调用计时器的cancel方法.

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.

这篇关于在Java中创建重复计时器提醒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆