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

Java ScheduledExecutorService ScheduleWithFixedDelay adding unexpected delay after some iterations?

我 运行 在 2 m/c 上安排程序 windows 但配置不同 -

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 毫秒。

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

你不能指望调度程序(在一台或多台机器上)每次都运行完全在同一时间。

我从 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应该可以帮助你理解原因。