Reputation: 63
I have a Task Scheduler running in my Micronaut Application as described here. What I want is an option to shutdown this task if I receive some kind of request from the user. How can I do that?
Upvotes: 1
Views: 910
Reputation: 9072
In order to cancel a scheduled task you need to work directly with the TaskScheduler
.
The following example explains cancelling of a job.
@Singleton
public class SomeBeanThatDoesScheduling {
private final TaskScheduler taskScheduler;
private ScheduledFuture<?> scheduledFuture;
public SomeBeanThatDoesScheduling(@Named(TaskExecutors.SCHEDULED) TaskScheduler taskScheduler) {
this.taskScheduler = taskScheduler;
}
// on application startup you can register your scheduled task
@EventListener
public void onStartup(StartupEvent startupEvent) {
scheduledFuture = taskScheduler.scheduleWithFixedDelay(initialDelay, interval, this::execute);
}
public void execute() {
System.out.println("The task has been executed");
}
// use this method to cancel the job
public void cancelTheJob() {
if (this.scheduledFuture != null) {
this.scheduledFuture.cancel(false);
}
}
}
Upvotes: 1