我目前遇到ScheduledExecutorService執行速度超過給定時間範圍的問題。Java ScheduledExecutorService執行速度超出預期
scheduleAtFixedRate指出後續執行可能遲了,但它不會等待詞後的給定時間。
GrabPutTask簡單地從源獲取信息,分配捕獲時間並將其發送到數據庫。由於時間間隔小於一秒,數據庫條目會給出重複條目的錯誤。
在上一個任務完成之後,是否有辦法在固定的時間執行任務?
我讀過here,表示隊列中的任務「聚集」,但沒有提供我的需求的解決方案。
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public static void main(String[] args)
{
//
..
//
//Creating the looping thread.
try
{
scheduler.scheduleAtFixedRate(new GrabPutTask(), (long) 1, (long) (seconds * 1000), TimeUnit.MILLISECONDS);
LOGGER.info(String.format("DBUpdater connected and running. (GetAddr: %s, SetAddr: %s, Poll Rate: %.2f, Sector Number: %s, Number of PLCs: %d)",
FROM_IP.split(":", 2)[0] + ":" + fromServer.getPort(), dataSource.getURL(), seconds, SECTOR, NUMBER_OF_PLCS_ON_MASTER));
}
catch (IllegalArgumentException ex)
{
LOGGER.log(Level.SEVERE, null, ex);
printUsage();
System.exit(1);
}
}
實施例執行的時間間隔:
Event Called: 2014/02/12 14:19:07.199
Event Called: 2014/02/12 14:19:08.199
Event Called: 2014/02/12 14:19:09.199
Event Called: 2014/02/12 14:19:10.199
Event Called: 2014/02/12 14:19:11.199
Event Called: 2014/02/12 14:19:12.199
Event Called: 2014/02/12 14:19:13.199
Event Called: 2014/02/12 14:19:14.199
Event Called: 2014/02/12 14:19:15.199
Event Called: 2014/02/12 14:19:16.199
Event Called: 2014/02/12 14:19:17.199
Event Called: 2014/02/12 14:19:18.199
...
Event Called: 2014/02/12 14:20:21.415 (A load on the server it seems)
Event Called: 2014/02/12 14:20:22.215
Event Called: 2014/02/12 14:20:23.425
Event Called: 2014/02/12 14:20:24.422
Event Called: 2014/02/12 14:20:25.276
Event Called: 2014/02/12 14:20:25.997
你看到'scheduleWithFixedDelay'方法在那之後嗎? – chrylis
@chrylis您應該將其作爲答案發布。它比我的'Thread.sleep()'答案小得多。 – Rainbolt
@John目前還不清楚這是OP的意圖。 – chrylis