代码之家  ›  专栏  ›  技术社区  ›  AlexK

Java执行器。scheduleAtFixedRate累加延迟

  •  0
  • AlexK  · 技术社区  · 9 年前

    我遇到了一些执行人延迟的问题。我的线程如下所示:

    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); 
    

    1 回复  |  直到 9 年前
        1
  •  1
  •   Jockie    9 年前

    这可能与你睡在线程中有关 Thread.sleep(MILISECONDS_TO_WAIT);

    [编辑] 您的问题的答案是,它将每X秒运行一次,并且从初始线程/下一个线程启动时开始计数,但如果线程在计划执行时不可用(因为线程处于休眠状态或例如执行非常繁重的计算),它将等待它变为可用。