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

gheorghi evgheniev
  • 558
  • 1
  • 7
  • 23

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,127
  • 6
  • 21