gpt4 book ai didi

Java ScheduledExecutorService 执行速度比预期快

转载 作者:行者123 更新时间:2023-12-01 23:12:15 26 4
gpt4 key购买 nike

我目前遇到了 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

最佳答案

如果执行因任何原因而延迟,

scheduleWithFixedRate 会尝试“ catch ”。您可以使用scheduleWithFixedDelay来阻止系统在上一次执行之后才启动时钟;延迟会累积并且不会 catch 。

关于Java ScheduledExecutorService 执行速度比预期快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21741672/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com