1

I am using @Scheduled annotation to initialize a task scheduled in my Spring Boot project.

@Override
@Scheduled(cron = "#{scanningTime}")
public void execution() {
    invitePlanScanner();
}

But I'm have difficulty to stopping it at runtime. My idea is to initialize a cron job in addition to using annotations that able to dynamically use the methods of the library. But after a period of research, I don't see that java provides a specific way to initialize a job with cron schedule along with a stop method.

Any one have an idea for this problem?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • I don't really understand the question. Are you asking on how to schedule tasks in java without Spring (`ScheduledExecutorService`) or how to [make a thread interruptable](https://stackoverflow.com/questions/3590000/what-does-java-lang-thread-interrupt-do)? – daniu May 30 '23 at 07:53
  • @daniu I mean I use annotation to start a cron job but I can't stop it during runtime. So I came up with an idea to use some library in addition to initializing that job with annotation. But I can't find a specific method to run the cron job and stop it at runtime (may be in catch block, or an api to stop it) – Thành Đặng May 30 '23 at 08:02
  • 1
    You can see a similar question [here](https://stackoverflow.com/questions/44644141/how-to-stop-a-scheduled-task-that-was-started-using-scheduled-annotation). – Shadow4571 May 30 '23 at 09:25

1 Answers1

0

You can use the "ThreadPoolTaskScheduler".

ScheduledFuture<?> schedule = taskScheduler.schedule(
  createRunnable(),
  new PeriodicTrigger(5, TimeUnit.SECONDS)
);
schedule.cancel(true);

See: https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/scheduling.html

Noixes
  • 1,158
  • 12
  • 25
  • `ThreadPoolTaskScheduler` does not implement from `ScheduledFuture>`. How you can declare like that? – Thành Đặng May 30 '23 at 09:19
  • @ThànhĐặng The return type of "schedule" is ScheduledFuture>. The signature is "public ScheduledFuture> schedule(Runnable task, Trigger trigger)" – Noixes May 31 '23 at 05:31