Puneet
Puneet

Reputation: 63

How to stop or cancel a running scheduled task?

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

Answers (1)

saw303
saw303

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

Related Questions