繁体   English   中英

在Java中完成前一个任务之后,以固定的时间安排定期任务

[英]schedule periodic task at a fixed duration after previous one finished in java

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

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

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

使用ScheduledExecutorServicescheduleWithFixedDelay方法可以做到这一点。 由于Executors工厂类,您可以获得此类执行器服务的实例。 此类是Timer的替代品,它有一些缺陷。

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

暂无
暂无

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

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