Denis Savrasov
Denis Savrasov

Reputation: 141

Start and stop scheduling task in Spring java

I develop a simple Spring Boot app that consumes REST and writes to DB.

I tried a @Scheduled annotation to initiate a task to run it periodically. But the scheduling process starts automaticly, which is not exactly what I want. I need an ability to start and stop a scheduled task from a web page. When a user opens a page he must see a status of a process : Running/Stoped.

What is the easy way to implement it? Create a new thread? How to get a status of a process? Save it in db?

Maybe smb has an example of starting and stoping schedduled task from web page?

Upvotes: 4

Views: 6104

Answers (1)

statut
statut

Reputation: 909

Try to use ScheduledExecutorService. For example, first of all create a ScheduledExecutorService:

ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());

then create a scheduled task:

ScheduledFuture<?> task = scheduledExecutorService.scheduleAtFixedRate(
() -> System.out.println("some task"), 0, 30, TimeUnit.SECONDS);

and when you want to cancel the task, do the following:

task.cancel(true);

Upvotes: 3

Related Questions