1 回答

TA貢獻(xiàn)1936條經(jīng)驗 獲得超7個贊
這可能是因為在 XML 中您使用固定速率,而在 Java 配置中您使用固定延遲。正如官方 Spring Doc所述:
...固定延遲指示每個任務(wù)執(zhí)行完成后等待的毫秒數(shù)。另一個選項是fixed-rate,表示該方法應(yīng)該多久執(zhí)行一次,而不管之前的執(zhí)行需要多長時間......
因此,如果您的示例中的某些代碼在某個時間間隔內(nèi)花費(fèi)的時間比您的固定費(fèi)率多得多,那么連續(xù)的任務(wù)可能剛剛在該時間間隔內(nèi)排隊。一旦完成繁重的執(zhí)行并且如果下一次執(zhí)行恰好是輕量級的,那么您將在日志中看到您在日志中看到的內(nèi)容,直到 ScheduledExecutorService 的隊列被耗盡。之后,您的輕量級任務(wù)將開始以固定速率毫秒運(yùn)行。
嘗試在日志中搜索第一次執(zhí)行以查看它們所花費(fèi)的時間。您還可以注釋掉一些代碼并重新啟動您的應(yīng)用程序以嘗試定位根本原因。下面是我的模擬示例,預(yù)計每 1 秒運(yùn)行一次,但第一次運(yùn)行需要 5 秒:
public class CacheManager {
private static final Logger LOG = LoggerFactory.getLogger(CacheManager.class);
private final AtomicInteger counter = new AtomicInteger();
public void updateConfigurations() throws InterruptedException {
LOG.info("update configurations");
if (counter.getAndIncrement() == 0) {
Thread.sleep(5000);
}
LOG.info("end update configurations");
}
public static void main(String[] args) {
new ClassPathXmlApplicationContext("spring.xml");
}
}
<beans ...>
<bean id="cacheManager" class="CacheManager"/>
<task:scheduler id="ttScheduler" pool-size="1"/>
<task:scheduled-tasks scheduler="ttScheduler">
<task:scheduled ref="cacheManager" method="updateConfigurations" fixed-rate="1000" initial-delay="0"/>
</task:scheduled-tasks>
</beans>
輸出:
21:00:58.703 [ttScheduler-1] INFO CacheManager - update configurations
21:01:03.706 [ttScheduler-1] INFO CacheManager - end update configurations
21:01:03.706 [ttScheduler-1] INFO CacheManager - update configurations
21:01:03.707 [ttScheduler-1] INFO CacheManager - end update configurations
21:01:03.707 [ttScheduler-1] INFO CacheManager - update configurations
21:01:03.707 [ttScheduler-1] INFO CacheManager - end update configurations
21:01:03.707 [ttScheduler-1] INFO CacheManager - update configurations
21:01:03.707 [ttScheduler-1] INFO CacheManager - end update configurations
21:01:03.707 [ttScheduler-1] INFO CacheManager - update configurations
21:01:03.708 [ttScheduler-1] INFO CacheManager - end update configurations
21:01:03.708 [ttScheduler-1] INFO CacheManager - update configurations
21:01:03.708 [ttScheduler-1] INFO CacheManager - end update configurations
21:01:04.707 [ttScheduler-1] INFO CacheManager - update configurations
21:01:04.708 [ttScheduler-1] INFO CacheManager - end update configurations
21:01:05.706 [ttScheduler-1] INFO CacheManager - update configurations
21:01:05.706 [ttScheduler-1] INFO CacheManager - end update configurations
21:01:06.704 [ttScheduler-1] INFO CacheManager - update configurations
21:01:06.704 [ttScheduler-1] INFO CacheManager - end update configurations
添加回答
舉報