每 X 秒 Java 线程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3541676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Thread every X seconds
提问by Manuel Selva
What is the easiest way to have a piece of Java code scheduled at a given rate ?
以给定速率安排一段 Java 代码的最简单方法是什么?
采纳答案by cletus
In Java 5+ with a ScheduledExecutorService
:
在 Java 5+ 中带有ScheduledExecutorService
:
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
// do stuff
}
}, 0, 5, TimeUnit.SECONDS);
The above method is favoured. Prior to Java 5 you used Timer
and TimerTask
:
上面的方法是首选。在 Java 5 之前,您使用Timer
和TimerTask
:
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// do staff
}
}, 0, 5000);
回答by developmentalinsanity
By using a ScheduledExecutorService.
Have a look at Executors.newScheduledThreadPool
. It will allow you to created a ScheduledExecutorService
which lets you submit Runnable
s to be executed at regular intervals.
看看Executors.newScheduledThreadPool
。它将允许您创建 a ScheduledExecutorService
,让您提交Runnable
s 以定期执行。
回答by flamming_python
while (true) {
thread.sleep(1000)
method();
}
In many cases there will be better alternatives. But this is the easiest way to implement a regular execution of your method() at an interval of 1000ms + n (where n is the amount of time spent executing method())
在许多情况下,会有更好的选择。但这是以 1000 毫秒 + n 的间隔定期执行 method() 的最简单方法(其中 n 是执行 method() 所花费的时间)
Of course instead of 1000, you can put any millisecond value you desire. It could also be an idea to implement the while loop on a flag that another thread controls; so that there is an way to stop execution of the loop without having to kill the program.
当然,您可以输入任何您想要的毫秒值而不是 1000。在另一个线程控制的标志上实现 while 循环也可能是一个想法;这样就有一种方法可以在不必终止程序的情况下停止循环的执行。
回答by Ramesh Thangaraj
Use below code :
使用以下代码:
Timer timer = new Timer();
timer.schedule( new TimerTask()
{
public void run() {
// do your work
}
}, 0, 60*(1000*1));