Reputation: 1439
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
Reputation: 54148
You can get an ScheduledExecutorService
from Executors
, get a SingleThread
version or a MultipleThread
Executors.newSingleThreadScheduledExecutor
Then provide the runnable
, the duration
and its TimeUnit
: ScheduledExecutorService.schedule(Runnable command, long delay, TimeUnit unit)
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
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