1

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?

Serhii Kachan
  • 345
  • 4
  • 13
  • Does this answer your question? [How to stop a scheduled task that was started using @Scheduled annotation?](https://stackoverflow.com/questions/44644141/how-to-stop-a-scheduled-task-that-was-started-using-scheduled-annotation) – sorifiend Apr 15 '21 at 11:55
  • @sorifiend, not fully, i'm looking for the solution how to start first scheduled task execution after some code has been run in program and finish then. Imagine a test with 5 steps - each step = some java method. I'd like to run scheduled task when test reaches 3rd step and until 4th step is finished. – Serhii Kachan Apr 15 '21 at 12:17

1 Answers1

2

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");
}
M A
  • 71,713
  • 13
  • 134
  • 174
  • 1
    Thanks for the answer, yes it is. But here the scheduled method will be still invoked forever, however it will do nothing. I'm looking for exactly enabling/disabling invocation fully from a spring configs. – Serhii Kachan Apr 15 '21 at 12:23
  • 1
    @СергійКачан Spring is not a magic thing that make all our wishes come true. IMO MA would be the closest possible thing for your use case. Otherwise you will have to really mess with schedulers and spring core and provide your own implementation, huge task for something achievable with only 1 line of code as M A indicated – Panagiotis Bougioukos Apr 15 '21 at 12:57