All Things Techie With Huge, Unstructured, Intuitive Leaps

Java: How to schedule an event for a specific time

In a previous blog entry, I showed a snippet of code on how to determine the amount of minutes from now to a specific time.

The code was quite simple:

Date now = new Date();
GregorianCalendar expiryDate = myevent.getExpiryDate();
Date end = expiryDate.getTime();
long difference = Math.abs(end.getTime() - now.getTime());
long minutesLeft = difference / (1000 * 60);



Starting from that point, it is quite simple to schedule a Java runnable thread at a specific time. Here is how I did it:

private ScheduledExecutorService scheduler;
.....
scheduler = Executors.newSingleThreadScheduledExecutor();

.....
Date now = new Date();
GregorianCalendar expiryDate = myevent.getExpiryDate();
Date end = expiryDate.getTime();
long difference = Math.abs(end.getTime() - now.getTime());
long minutesLeft = difference / (1000 * 60);
long secondsLeft = difference / 1000;
// task to run is embedded in a class implementing Runnable
RunnableNow runnableNow = new RunnableNow()
scheduler.schedule(uhuraNow, secondsLeft, TimeUnit.SECONDS);


Hope this snippet save someone some time

No comments:

Post a Comment