Serhii Kachan
Serhii Kachan

Reputation: 403

How to start/stop @Scheduled task after certain method finishes

I have a scheduled task that start working when application context loads and runs forever until program ends.

I'd like to save some resources and run scheduled task only when it's needed.

Here is abstract code I imagine how it should work like.

@EnableScheduling    
public class Scheduling {
    
        @Scheduled(fixedRate = 1000)
        public void scheduledTask() {
           log.info("scheduled task has been started");
        }
    
        public void triggerStart() {
           log.info("after this @Scheduled task will start working");
        }
    
        public void triggerFinish() {
           log.info("after this @Scheduled task will stop working");
        }
}

I'm curious is it possible to achieve such result?

Upvotes: 1

Views: 2162

Answers (1)

M A
M A

Reputation: 72884

A very simple way is to add a boolean switch:

@Scheduled(fixedRate = 1000)
public void scheduledTask() {
   if (enabled) {
       log.info("scheduled task has been started");
   }
}

public void triggerStart() {
   enabled = true;
   log.info("after this @Scheduled task will start working");
}

public void triggerFinish() {
   enabled = false;
   log.info("after this @Scheduled task will stop working");
}

Upvotes: 1

Related Questions