Java executor.scheduleAtFixedRate加起来延迟

时间:2017-07-18 15:23:38

标签: java multithreading

我遇到了遗嘱执行人延迟的一些问题。我的主题看起来像这样:

public void run() {
    logger.log("Starting " + tso.getName() + " for " + dataType);
    List<String[]> allRows = new ArrayList<String[]>();
    String[] lastRow;
    LocalDateTime lastDate;;
    LocalDateTime lastQuarterHour;
    while (true) {
        try {
            // Make attempt to take CSV data for today. If there is no data wait several seconds and try again
            allRows = getCSVRows();
            if (allRows == null || allRows.isEmpty()) {
                logger.log("Sleeping thread due to empty list for TSO " + tso.getName() + " and data type " + dataType);
                Thread.sleep(MILISECONDS_TO_WAIT);
                continue;
            }
            lastRow = allRows.get(allRows.size() - 1);
            lastDate = convertStringToUTC(lastRow[0] + " " + lastRow[2]);
            lastQuarterHour = takeLastQuorterHourTime();

            // If CSV data is available take the last record if it is before last quarter hour wait SEVERAL seconds and try again
            if (lastDate.isBefore(lastQuarterHour)) {
                logger.log("Sleeping due to lack of information for the current quarter for TSO " + tso.getName() + " and data type " + dataType);
                Thread.sleep(MILISECONDS_TO_WAIT);
            } else {
                break;
            }
        } catch (InterruptedException e) {
            logger.log(e.getMessage());
        }

    }
  }
}

第一次运行我的线程时,延迟是正常的,但是当线程休眠2或3次时,下一个线程周期开始时的延迟不是在以下内容中定义的:

executor.scheduleAtFixedRate(extractorThread, 0, WAIT_INTERVAL_MINUTES, TimeUnit.SECONDS); 

那么,延迟何时开始,一旦线程完成2-3次休眠并终止或线程本身启动,无论它工作多长时间?

1 个答案:

答案 0 :(得分:1)

这可能与您在线程内部睡觉的事实有关 Thread.sleep(MILISECONDS_TO_WAIT);

尝试删除它们并查看问题是否仍然存在

[编辑] 您的问题的答案是,它将每X秒运行一次,它从初始线程/下一个线程启动时开始计算,但是如果线程在计划执行时不可用(由于线程正在休眠或者例如做很重的计算)它会等待它变得可用。