我有以下3个类(class):
成分A
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个Scheduled方法并行运行,根据我得到的输出,这显然不是问题。我读到应该可以为@Schedule批注提供一个自定义TaskExecutor,用它可以定义我们想要多少个线程...
我对吗 ?我找不到如何提供此信息。
最佳答案
The documentation明确指出: