navy1978
navy1978

Reputation: 1439

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?

Upvotes: 2

Views: 4877

Answers (2)

azro
azro

Reputation: 54148


If you want to set a duration :

ScheduledExecutorService exe = Executors.newSingleThreadScheduledExecutor();
// or Executors.newScheduledThreadPool(2); if you have multiple tasks
exe.schedule(() -> System.out.println("Executed at:" + (new Date())), 1, TimeUnit.MINUTES);

If you want to use a LocalDateTime :

ScheduledExecutorService exe = Executors.newSingleThreadScheduledExecutor();
// or Executors.newScheduledThreadPool(2); if you have multiple tasks
LocalDateTime date = LocalDateTime.of(2018, 6, 17, 18, 30, 0);
exe.schedule(
       () -> System.out.println("Executed at:" + (new Date())),
       LocalDateTime.now().until(date, ChronoUnit.MINUTES),
       TimeUnit.MINUTES);

Upvotes: 6

xingbin
xingbin

Reputation: 28269

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

Upvotes: 2

Related Questions