Skip to content

Instantly share code, notes, and snippets.

@alexstolr
Created June 16, 2019 06:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexstolr/f870ca01aac22c49fdeadd5d02d0ef0e to your computer and use it in GitHub Desktop.
Save alexstolr/f870ca01aac22c49fdeadd5d02d0ef0e to your computer and use it in GitHub Desktop.
Dynamically enable/disable spring scheduled method
1) add TaskScheduler spring bean:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@Configuration
public class AppConfig {
@Bean
public TaskScheduler threadPoolTaskScheduler() {
return new ThreadPoolTaskScheduler();
}
}
2) Autowire the TaskScheduler and use ScheduledFuture to enable and disable the scheduled method:
@Qualifier("threadPoolTaskScheduler")
@Autowired
private TaskScheduler taskScheduler;
@Value("${timeout.from.properties.file}")
private String fixedRate;
private ScheduledFuture<?> scheduledFuture;
public void initScheduling(){
scheduledFuture = taskScheduler.scheduleAtFixedRate(this::terminateScheduledMethod, Integer.valueOf(fixedRate));
}
public void terminateScheduledMethod() {
if( /* Some condition for stopping schedule*/){
scheduledFuture.cancel(true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment