弹簧@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注释,通过它应该可以定义我们想要多少线程......
我说的对吗?我找不到如何提供此信息。