【问题标题】:Java ScheduledExecutorService executing faster than intendedJava ScheduledExecutorService 执行速度比预期快
【发布时间】: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


【解决方案1】:

scheduleWithFixedRate 尝试“赶上”如果执行因任何原因延迟。您可以使用scheduleWithFixedDelay 来阻止系统启动时钟,直到上一次执行之后;延迟会累积,不会赶上。

【讨论】:

    【解决方案2】:

    睡任意长的时间。

    try {
        Thread.sleep(someTime);
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-18
      • 2015-10-08
      相关资源
      最近更新 更多