Reputation: 2520
Collegues, I have a group of tasks that are scheduled. In spring-boot properties file it looks like:
group1.task1.run = <execute every first minute>
group1.task2.run = <execute every second minute>
group2.task1.run = <execute every first minute>
group2.task2.run = <execute every second minute>
Is it possible to create two different threads (T1
and T2
) and assign the first group of scheduled tasks to be executed in T1
thread, and the second group in T2
thread?
I can’t just increase PoolSize
in TaskScheduler
beacuse after that group1
tasks will be execute in different threads, it is not suitable for business process.
I would be grateful for any advice and help.
Upvotes: 0
Views: 1068
Reputation: 3311
As far as I know it's not possible to specify a single thread. However, you can specify the Executor
which should be used to schedule your tasks. If you wan't your tasks to be executed in the same thread, just create a thread pool with a single thread in it, like so:
@Configuration
@EnableAsync
@EnableScheduling
public class TempConfig {
@Scheduled(fixedRate = 1000)
@Async(value = "threadPool1")
public void task1() {
System.out.println("Task1: " + Thread.currentThread());
}
@Scheduled(fixedRate = 1000)
@Async(value = "threadPool2")
public void task2() {
System.out.println("Task2: " + Thread.currentThread());
}
@Bean
public Executor threadPool1() {
return Executors.newFixedThreadPool(1);
}
@Bean
public Executor threadPool2() {
return Executors.newFixedThreadPool(1);
}
}
Of course, you can alternatively just schedule the tasks yourself:
var s1 = Executors.newScheduledThreadPool(1);
var s2 = Executors.newScheduledThreadPool(1);
// schedule tasks of group1
s1.scheduleWithFixedDelay(...);
s1.scheduleWithFixedDelay(...);
// schedule tasks of group2
s2.scheduleWithFixedDelay(...);
s2.scheduleWithFixedDelay(...);
Upvotes: 3