spring Scheduler - 配置中指定的两个 Scheduler Bean

发布于 2025-01-11 12:36:53 字数 1068 浏览 1 评论 0原文

在我的应用程序中,我为 TaskScheduler 定义了一个 bean,池大小为 5,因为我的应用程序中有多个 @Scheduled 方法,并且要求它们应该能够运行并行而不是在同一线程上(这是 Spring Scheduler 的默认配置)。

@Bean
public TaskScheduler taskScheduler() {
    final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.setPoolSize(5);
    return scheduler;
}

我不知道已经存在这样的调度程序线程池:

@Bean
@Autowired
public Executor taskScheduler(MyThreadPoolService myThreadPoolService) {
    return myThreadPoolService.newScheduledThreadPool("Concurrency.Task-Scheduler");//Concurrency.Task-Scheduler is threadpool name.
}

现在我的应用程序有两个 bean,但在我的日志中我注意到运行 @Scheduled 方法的线程是“Concurrency.Task-Scheduler- Thread-1”,即已定义的线程,并且所有 @Scheduled 方法都在同一线程“Concurrency.Task-Scheduler-Thread-1”上运行。

我还注意到,在测试时,我一次又一次地重新启动应用程序,有时 @Scheduled 方法在第一个配置中配置的不同线程上运行,即打印不同的线程名称 taskScheduler-1、taskScheduler-2意味着我的第一个配置中的线程池正在被拾取。

我无法理解这是怎么发生的。有时使用“taskScheduler”线程池,有时使用“Concurrency.Task-Scheduler”,这是怎么回事?不应该有bean冲突吗?

In my application I had defined a bean for TaskScheduler with pool size of 5 as there are multiple @Scheduled methods in my application and it was required that they should be able to run in parallel and not on same thread (which is default configuration of Spring Scheduler).

@Bean
public TaskScheduler taskScheduler() {
    final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.setPoolSize(5);
    return scheduler;
}

I was unaware that there already exists a scheduler thread pool like this:

@Bean
@Autowired
public Executor taskScheduler(MyThreadPoolService myThreadPoolService) {
    return myThreadPoolService.newScheduledThreadPool("Concurrency.Task-Scheduler");//Concurrency.Task-Scheduler is threadpool name.
}

Now my application has both the beans but in my logs I notice that the thread running the @Scheduled methods is "Concurrency.Task-Scheduler-Thread-1" i.e. the already defined one and all the @Scheduled methods are running on the same thread "Concurrency.Task-Scheduler-Thread-1".

I have also noticed that when testing I restart the application again and again, sometimes the @Scheduled methods run on different threads as configured in first configuration i.e. different thread names are printed taskScheduler-1, taskScheduler-2 which means the threadpool from my first configuration is being picked up.

I am unable to understand how this is happening. How is it that sometimes "taskScheduler" threadpool is used and sometimes "Concurrency.Task-Scheduler". Shouldn't there be a bean conflict ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文