Using java.time
The Answer by Tulupov using ScheduledExecutorService
is correct and should be accepted. Here I address the date-time angle.
If possible, serialize your date-time values to text using standard ISO 8601 formats.
2017-04-10T09:00:00Z
2017-04-10T11:00:00Z
2017-04-11T15:30:00Z
The java.time classes use ISO 8601 formats by default when parsing and generating date-time values.
Instant instant = Instant.parse( "2017-04-10T09:00:00Z" );
Also, you ignore the critical issue of time zones. The Z
on my strings above are short for Zulu
and mean UTC. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
If you must work with strings in those unfortunate formats, search Stack Overflow for the DateTimeFormatter
class to learn more on parsing strings.
If your date-times are meant for some other region’s wall-clock time, then assign a time zone via ZoneId
to get a ZonedDateTime
. Search Stack Overflow for those class names to learn much more.
You need to get a number of milliseconds to schedule the event with ScheduledExecutorService
. You must calculate the number of milliseconds between the current moment and the desired Instant
of the event. Such a span of time is represented by the Duration
class as a total number of seconds plus a fractional second in nanoseconds. You can ask the Duration
for its total span of time as a count of milliseconds (truncating any microseconds/nanoseconds).
Instant now = Instant.now() ;
Duration d = Duration.of( now , instant ) ;
long millis = d.toMillis();
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.