0

I'm trying to do a Thread.sleep within a @Scheduled(fixedDelay) block, but so far no luck. From what i read and saw, Thread.sleep doesn't work under @Scheduled. I can think of a while loop but i don't feel that confident on that approach. Do you guys have any other suggestions ?

I'm running multiple tasks under this scheduler and I need to put some delays in between some of them. There is no question of splitting these tasks into multiple schedulers. Everything has to be done under the same one.

Thanks

Yonoss
  • 1,242
  • 5
  • 25
  • 41
  • Are there any condition for task after which thread should sleep? Maybe after N count of tasks? – Egor Sep 24 '20 at 14:33
  • There isn't a clear pattern on when those sleeps must be called. They have to be called based on the output of previous tasks under some circumstances . So it is random. – Yonoss Sep 24 '20 at 14:36
  • But when thread should wake up? – Egor Sep 24 '20 at 14:38
  • It might help you https://stackoverflow.com/questions/31882624/thread-delay-using-scheduler-or-thread-sleep – Hasanuzzaman Rana Sep 24 '20 at 14:43

1 Answers1

0

You can create atomic flag that will signal if thread should be slept.

private static final AtomicBoolean sleep = new AtomicBoolean(false);

@Scheduled(...)
public void schedule() {
    sleep.set(true);
}

public void process() {
    new Thread(() -> {
        while (true) {
            if (sleep.get()) {
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sleep.set(false);
            }
            
            doSmth();
        }
    }).start();
}
Egor
  • 1,334
  • 8
  • 22