Java ScheduledExecutorService ScheduleWithFixedDelay在一些迭代后添加意外延迟?

时间:2016-01-28 10:21:17

标签: java scheduledexecutorservice

我在2 m / c两个窗口运行调度程序,但配置不同 -

public class testScheduling {
    static boolean header = false;
    static ScheduledExecutorService m_scheduleService;
    public static void main(String[] args) throws IOException {

        WorkerThread worker = new WorkerThread();
        m_scheduleService = Executors.newScheduledThreadPool(1);

        m_scheduleService.scheduleWithFixedDelay(worker, 1, 1,  TimeUnit.MILLISECONDS);

    }



     static public class WorkerThread implements Runnable{

            public WorkerThread(){
            }

            @Override
            public void run() {
                try {
                    processCommand();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    System.out.println("something wrong in thread");
                    e.printStackTrace();
                }
            }

            private void processCommand() throws InterruptedException {
                Date d = new Date();
                System.out.println("print ...." + Utility.getDateToString(d));

            }

        }
}

在1 m / c时,结果为 -

print ....2016-01-28 15:42:45.289
print ....2016-01-28 15:42:45.289
print ....2016-01-28 15:42:45.289
print ....2016-01-28 15:42:45.289
print ....2016-01-28 15:42:45.289
print ....2016-01-28 15:42:45.289
print ....2016-01-28 15:42:45.289
print ....2016-01-28 15:42:45.299
print ....2016-01-28 15:42:45.299
print ....2016-01-28 15:42:45.299
print ....2016-01-28 15:42:45.299
print ....2016-01-28 15:42:45.299

----经过一段间隔10毫秒的差异。

在另一个m / c上,结果是

print ....2016-01-28 05:06:54.239
print ....2016-01-28 05:06:54.239
print ....2016-01-28 05:06:54.239
print ....2016-01-28 05:06:54.239
print ....2016-01-28 05:06:54.239
print ....2016-01-28 05:06:54.239
print ....2016-01-28 05:06:54.255
print ....2016-01-28 05:06:54.255
print ....2016-01-28 05:06:54.255
print ....2016-01-28 05:06:54.255
print ....2016-01-28 05:06:54.255
print ....2016-01-28 05:06:54.255

- 一些迭代后的第二个m / c显示差异为16 ms。

为什么2种不同的m / c有这种差异? 为什么在一些迭代后有很长的延迟? 可以消除这种意外延迟吗?

1 个答案:

答案 0 :(得分:0)

您不能指望调度程序(在一台或多台计算机中)每次都在同一时间运行。

我在ScheduledExecutorService

的java文档中引用了以下注意事项
Beware however that expiration of a relative delay need not coincide with the current Date at 
which the task is enabled due to network time synchronization protocols, clock drift, 
or other factors.

Reference java doc link

NTP应该能够帮助您了解原因。