Skip to content
Advertisement

Using Spring Framework Scheduler in a non-bean class

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?

Advertisement

Answer

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:

  1. Create a spring bean (I understand, you already have spring, hence the question) that will create your legacy class, or maybe will access it via some legacy global registry – it really depends on your project:
@Component
public class MySpringBean {

   @Scheduled (...)
  public void scheduledStuff()  {

      MyLegacyClass c = MyLegacyGlobalContext.getMyLegacyClass();
      c.callMyLegacyMethod();
   }
}
  1. Implement the scheduling entirely outside the spring:
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);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement