![](/img/trans.png)
[英]ScheduledExecutorService not executing task with an initialDelay 0
[英]Java ScheduledExecutorService executing faster than intended
我目前遇到的問題是ScheduledExecutorService的執行速度超過了給定的時間范圍。
scheduleAtFixedRate指出后續執行可能會延遲,但不會等待給定時間的后記。
GrabPutTask只是從源中獲取信息,分配捕獲時間,然后將其發送到數據庫。 因為間隔小於一秒,所以數據庫條目在重復條目方面給出了錯誤。
有沒有辦法在上一個任務完成之后的固定時間執行任務?
我在這里已經讀到,任務“排成一排”,但是沒有提出我需要的解決方案。
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
如果執行由於某種原因而延遲, scheduleWithFixedRate
嘗試“追趕”。 您可以使用scheduleWithFixedDelay
來防止系統從開始計時直到上一次執行為止。 延遲會累積,不會趕上。
可以睡任何時間。
try {
Thread.sleep(someTime);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.