简体   繁体   中英

Shutdown a @Scheduled task in Spring

I'm in the following situation: a ThreadPoolScheduler and two methods annotated with @Scheduled.

@Bean
public ThreadPoolTaskScheduler serviceRegistryTaskScheduler() {
    final ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
    threadPoolTaskScheduler.setPoolSize( 2 );
    return threadPoolTaskScheduler;
}

@Scheduled( initialDelay = 3000, fixedDelay = 3000 )
public void methodOne() {
    // do this
}

@Scheduled( initialDelay = 3000, fixedDelay = 3000 )
public void methodTwo() {
    // do that
}

I basically want to stop one of the two @Scheduled methods. Is there a way to do it?

It is quite rare to have @Scheduled tasks which have different life-cycle than the Application context they live in, so I don't think there is a way you can just stop them, unless you dig in to the TaskScheduler internals.

However, you could put the beans into their own little spring context, and have the current application context as a parent context. This way you can start and stop the child context when you need.

Another, slightly dirtier variation, is to have a single context, but put the @Scheduled methods into a @Component, and then call context.getBeanFactory().destroyBean(component); when you want to stop the scheduling. If you need to start it again, you will need to create and register the component again - hense the not so pretty as the first solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM