在上一个完成java之后,在固定的持续时间内安排定期任务

时间:2011-11-05 20:14:02

标签: java timer scheduled-tasks schedule

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

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

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

2 个答案:

答案 0 :(得分:4)

使用ScheduledExecutorService的{​​{3}}方法,就是这样做的。由于scheduleWithFixedDelay工厂类,您可以获得此类执行程序服务的实例。这个类是Timer的替代品,它有一些不足之处。

答案 1 :(得分:1)

您可以在任务完成后安排下一次执行,而不是使用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);
}
相关问题