我在遗留项目中使用了Spring,并且希望在一个类中使用“调度”运行,这个类不是作为bean创建的,而是作为一个通常的“新”类创建的。因此,诸如@Scheduled这样的注解是不活动的。
然后如何通过显式调用所有相关的Spring方法来启用调度?
发布于 2021-08-05 15:14:39
基本上您不能这样做,因为spring只能在由Spring管理的类上使用它的“魔力”(在本例中是确定调度规则并定期调用该方法)。
如果必须手动创建类,则不能在其上放置@Scheduled注释。
所以你的选择是:
。
@Component
public class MySpringBean {
@Scheduled (...)
public void scheduledStuff() {
MyLegacyClass c = MyLegacyGlobalContext.getMyLegacyClass();
c.callMyLegacyMethod();
}
}ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(5);
ScheduledFuture scheduledFuture =
scheduledExecutorService.schedule(new Callable() {
public Object call() throws Exception {
MyLegacyClass c = MyLegacyGlobalContext.getMyLegacyClass();
c.callMyLegacyMethod();
}
},
30,
TimeUnit.MINUTES);https://stackoverflow.com/questions/68667641
复制相似问题