简体   繁体   English

Java Thread每隔X秒

[英]Java Thread every X seconds

以给定速率安排一段Java代码的最简单方法是什么?

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之前,您使用了TimerTimerTask

timer.scheduleAtFixedRate(new TimerTask() {
  @Override
  public void run() {
    // do staff
  }
}, 0, 5000);

By using a ScheduledExecutorService . 通过使用ScheduledExecutorService

Have a look at Executors.newScheduledThreadPool . 看看Executors.newScheduledThreadPool It will allow you to created a ScheduledExecutorService which lets you submit Runnable s to be executed at regular intervals. 它将允许您创建一个ScheduledExecutorService ,它允许您定期执行Runnable

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()) 但这是以1000ms + n的间隔实现method()的常规执行的最简单方法(其中n是执行method()所花费的时间)

Of course instead of 1000, you can put any millisecond value you desire. 当然,不是1000,你可以把你想要的任何毫秒值。 It could also be an idea to implement the while loop on a flag that another thread controls; 在另一个线程控制的标志上实现while循环也是一个想法; so that there is an way to stop execution of the loop without having to kill the program. 这样就有办法停止执行循环而不必杀死程序。

Use below code : 使用以下代码:

Timer timer = new Timer(); 
timer.schedule( new TimerTask() 
{ 
    public void run() { 
    // do your work 
    } 
}, 0, 60*(1000*1));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM