Search code examples
javatimertaskscheduledexecutorservice

Use ScheduledExecutorService to run code at specific Date time only once


I have a code that has to be executed at a certain date time in the future, let's say that I have a future date and I want to execute a peace of code in that date +1 minute in the future, but only once. I know I to do this with a java Timer and TimerTask .For example doing something like this:

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class Main {

    public static void main(String[] args) {

        Calendar myDate = Calendar.getInstance();
        myDate.add(Calendar.MINUTE, 1);
        Date afterOneMinute = myDate.getTime();
        System.out.println("Scheduled at:" + afterOneMinute);
        Timer timer = new Timer();

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("Executed at:" + (new Date()));

            }
        }, afterOneMinute);
    }

}

I'm looking for an elegant way to to the same using ScheduledExecutorService, in order to have a specific pool, because this pool will be used for multiple calls. Does somebody can help me?


Solution

  • You can use ScheduledExecutorService.schedule(Runnable command, long delay, TimeUnit unit)

    long delay = afterOneMinute.getTime() - System.currentTimeMillis();
    ScheduledExecutorService executorService = ...;
    executorService.schedule(runnable, delay, TimeUnit.MILLISECONDS);