弹簧@Scheduler并联运行

2022-09-02 12:05:20

我有以下3个班级:

Componanta

package mytest.spring.test.spring;

import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ComponentA {

    Logger log = Logger.getLogger(ComponentB.class);

    @Scheduled(fixedRate=2000)
    public void sayHello() {
        for(int i=1 ; i<=5 ; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            log.info("Hello from ComponentA " + i);
        }
    }
}

组件 B

package mytest.spring.test.spring;

import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ComponentB {

    Logger log = Logger.getLogger(ComponentB.class);

    @Scheduled(fixedRate=2000)
    public void sayHello() {
        for(int i=1 ; i<=3 ; i++) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            log.info("Hello from ComponentB " + i);
        }
    }
}

我的应用程序

package mytest.spring.test.spring;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

当我执行它时,我得到以下输出:

Hello from ComponentA 1
Hello from ComponentA 2
Hello from ComponentA 3
Hello from ComponentA 4
Hello from ComponentA 5
Hello from ComponentB 1
Hello from ComponentB 2
Hello from ComponentB 3
Hello from ComponentA 1
Hello from ComponentA 2
Hello from ComponentA 3
Hello from ComponentA 4
Hello from ComponentA 5
Hello from ComponentB 1
Hello from ComponentB 2
Hello from ComponentB 3
...

我需要2个计划方法并行运行,根据我得到的输出,这显然不是cae。我读到应该可以用自定义的TaskExecutor提供@Schedule注释,通过它应该可以定义我们想要多少线程......

我说的对吗?我找不到如何提供此信息。


答案 1

该文件明确指出:

默认情况下,将搜索关联的调度程序定义:上下文中的唯一bean,或者名为“taskScheduler”的bean;还将对 Bean 执行相同的查找。如果两者都不可解析,则将在注册器中创建并使用本地单线程默认计划程序。TaskSchedulerTaskSchedulerScheduledExecutorService

当需要更多的控制时,@Configuration类可以实现调度配置器。这允许访问底层 ScheduledTaskRegistrar 实例。例如,下面的示例演示如何自定义用于执行计划任务的执行程序:

@Configuration
@EnableScheduling
public class AppConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
    }

    @Bean(destroyMethod="shutdown")
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(100);
    }
}

答案 2

推荐