Created
June 16, 2019 06:55
-
-
Save alexstolr/f870ca01aac22c49fdeadd5d02d0ef0e to your computer and use it in GitHub Desktop.
Dynamically enable/disable spring scheduled method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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