【问题标题】:schedule periodic task at a fixed duration after previous one finished in java在java中完成前一个任务后,在固定的持续时间内安排周期性任务
【发布时间】:2011-12-22 19:18:39
【问题描述】:

我编写了一个使用Timer.scheduleAtFixedRate 定期运行线程的应用程序,如下所示:

this.ExtractorTimer=new Timer();
this.ExtractorTimer.scheduleAtFixedRate(new java.util.TimerTask() {
    public void run() {
        ...
    }
},0, 120000);

这会在特定时间(例如 2 分钟)后运行下一个线程,如果当前线程未完成,它将在当前线程完成后运行下一个线程。
我需要下一个线程在当前线程完成后一段时间后运行。
我怎样才能做到这一点?

【问题讨论】:

    标签: java timer scheduled-tasks schedule


    【解决方案1】:

    使用ScheduledExecutorServicescheduleWithFixedDelay 方法,正是这样做的。感谢Executors 工厂类,您可以获得这样一个执行器服务的实例。这个类是Timer的替代品,有一些不足。

    【讨论】:

      【解决方案2】:

      您可以在任务完成后安排下一次执行,而不是使用scheduleAtFixedRate

      public void initTimer() {
          Timer timer = new Timer();
          scheduleTask(timer);
      }
      
      
      private void scheduleTask(final Timer timer) {
          timer.schedule(new TimerTask() {
              public void run() {
                  // perform task here
      
                  scheduleTask(timer);
              }
          }, 120000);
      }
      

      【讨论】:

        猜你喜欢
        • 2015-06-10
        • 2016-05-24
        • 1970-01-01
        • 1970-01-01
        • 2014-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-29
        相关资源
        最近更新 更多