Reputation: 9411
I have Spring used in a legacy project and would like to use "Scheduled" runs in a class that is not created as a bean, but as a usual "new" class. So annotations such as @Scheduled are not active.
How can I then enable scheduling by calling all relevant Spring methods explicitly?
Upvotes: 0
Views: 873
Reputation: 42481
Basically you can't do that, because Spring can use its "magic" (in this case figure out the scheduling rules and invoke the method periodically) only on classes which are managed by spring.
If you have to create the class manually - you can't place a @Scheduled
annotation on it.
So Your options are:
@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);
Upvotes: 2