Spring:取消@Scheduled带注释的任务

时间:2017-07-27 12:22:50

标签: java spring spring-boot spring-scheduled

我正在运行一个Spring Boot应用程序,并尝试使用@Scheduled注释以特定延迟运行两个作业。

我想在特定条件下以编程方式取消这些作业。建议的方法是什么?以下是我的应用程序的配置:

Main.java

@SpringBootApplication
@EnableScheduling
public class Main implements CommandLineRunner {

  static LocalDateTime startTime = LocalDateTime.now();

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication(Main.class);
    app.setBannerMode(Banner.Mode.OFF);
    app.run(args);
  }

  @Override
  public void run(String... args) throws Exception {
  }

}

Job1.java

@Component
public class Job1 {

  @Scheduled(fixedDelay = 10000)
  public void run() {
    System.out.println("Job 1 running");
  }

}

Job2.java

@Component
public class Job1 {

  @Scheduled(fixedDelay = 10000)
  public void run() {
    System.out.println("Job 2 running");
  }

}

2 个答案:

答案 0 :(得分:2)

您需要通过Spring TaskScheduler界面的其中一个实施计划任务,例如TimerManagerTaskSchedulerThreadPoolTaskScheduler,获取ScheduledFuture个对象。

public interface TaskScheduler {

    ScheduledFuture schedule(Runnable task, Trigger trigger);

    ScheduledFuture schedule(Runnable task, Date startTime);

    ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period);

    ScheduledFuture scheduleAtFixedRate(Runnable task, long period);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay);

}

ScheduledFuture object提供取消任务的方法(ScheduledFuture.cancel())

答案 1 :(得分:0)

计划方法有预定的未来。在您的方法中获取此未来的句柄,然后您可以调用取消来取消该作业 您可以参考Spring-Boot stop Scheduled Task started using @Scheduled annotationstop Spring Scheduled execution if it hangs after some fixed time