Java Thread every X seconds

后端 未结 4 1647
旧巷少年郎
旧巷少年郎 2020-12-07 22:45

What is the easiest way to have a piece of Java code scheduled at a given rate ?

相关标签:
4条回答
  • 2020-12-07 23:06
    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())

    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.

    0 讨论(0)
  • 2020-12-07 23:10

    Use below code :

    Timer timer = new Timer(); 
    timer.schedule( new TimerTask() 
    { 
        public void run() { 
        // do your work 
        } 
    }, 0, 60*(1000*1));
    
    0 讨论(0)
  • 2020-12-07 23:12

    In Java 5+ with a 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:

    timer.scheduleAtFixedRate(new TimerTask() {
      @Override
      public void run() {
        // do staff
      }
    }, 0, 5000);
    
    0 讨论(0)
  • 2020-12-07 23:19

    By using a ScheduledExecutorService.

    Have a look at Executors.newScheduledThreadPool. It will allow you to created a ScheduledExecutorService which lets you submit Runnables to be executed at regular intervals.

    0 讨论(0)
提交回复
热议问题