【发布时间】:2014-02-12 22:54:23
【问题描述】:
我目前遇到的问题是 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 您应该将其发布为答案。它比我的
Thread.sleep()答案要小得多。 -
@John 目前尚不清楚这就是 OP 想要的。
-
@chrylis 抱歉不清楚。这正是我一直在寻找的!请张贴作为答案,我会+你。谢谢。
标签: java concurrency fixed scheduledexecutorservice