1 回答
TA贡献1936条经验 获得超6个赞
这可能是因为在 XML 中您使用固定速率,而在 Java 配置中您使用固定延迟。正如官方 Spring Doc所述:
...固定延迟指示每个任务执行完成后等待的毫秒数。另一个选项是fixed-rate,表示该方法应该多久执行一次,而不管之前的执行需要多长时间......
因此,如果您的示例中的某些代码在某个时间间隔内花费的时间比您的固定费率多得多,那么连续的任务可能刚刚在该时间间隔内排队。一旦完成繁重的执行并且如果下一次执行恰好是轻量级的,那么您将在日志中看到您在日志中看到的内容,直到 ScheduledExecutorService 的队列被耗尽。之后,您的轻量级任务将开始以固定速率毫秒运行。
尝试在日志中搜索第一次执行以查看它们所花费的时间。您还可以注释掉一些代码并重新启动您的应用程序以尝试定位根本原因。下面是我的模拟示例,预计每 1 秒运行一次,但第一次运行需要 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
添加回答
举报