我目前遇到的问题是 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