Mani
Mani

Reputation: 87

Schedule Thread only once.

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);
}

Upvotes: 0

Views: 670

Answers (1)

Gaurav Pathak
Gaurav Pathak

Reputation: 2593

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();

Upvotes: 1

Related Questions