0

How to fix my thread to schedule initial delay of thread for 2 min and don't schedule it again. (i.e., schedule only for once)

@Scheduled(fixedDelay = 5000)
public void myJob() {
     Thread.sleep(12000);
}
Mani
  • 87
  • 7
  • https://stackoverflow.com/questions/30347233/spring-scheduling-task-run-only-once – Reimeus Dec 03 '18 at 21:13
  • 1
    Possible duplicate of [Spring scheduling task - run only once](https://stackoverflow.com/questions/30347233/spring-scheduling-task-run-only-once) – Mohsen Dec 03 '18 at 21:15

1 Answers1

1

You can use ScheduledExecutorService in this case. It is an ExecutorService that can schedule commands to run after a given delay, or to execute periodically.

ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit)

Creates and executes a ScheduledFuture that becomes enabled after the given delay.

callable - the function to execute
delay - the time from now to delay execution
unit - the time unit of the delay

  ScheduledExecutorService service = null;

    service = Executors.newScheduledThreadPool(1);

    service.schedule(() -> {
        myMethodNameWhichIWantToExecute();
    }, 2, TimeUnit.MINUTES);

    if (service != null) service.shutdown();
Gaurav Pathak
  • 2,576
  • 1
  • 10
  • 20