如何停止或取消 运行 计划任务?

How to stop or cancel a running scheduled task?

我的 Micronaut 应用程序中有一个任务计划程序 运行,如 here 所述。如果我收到用户的某种请求,我想要的是关闭此任务的选项。我该怎么做?

要取消计划任务,您需要直接使用 TaskScheduler

以下示例说明了作业的取消。

@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);
    }
  }
 
}