Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger events in java at specific date and time?

I need to send sms to few mobile nos at specific date and time. e.g. I will have a list of dates and times and list of corresponding mobile nos. as below.

Date                Mobile
10th April 9 AM     1234567890
10th April 11 AM    9987123456,9987123457
11th April 3.30 PM  9987123456

and so on.

I know, java has cron schedulers which can run at specific schedule.

http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html

I can run a job which can keep on checking the time and then if the current time matches with time in above list, send the sms.

But in this case I will have to keep on checking all the time.

Is there any way, i can fire those events/sms directly at given time. Something like registering jobs for each of the date time and firing those at that time instead of having a job that runs continuously to check for date times ?

like image 748
sam Avatar asked Apr 08 '17 03:04

sam


2 Answers

You can use ScheduledExecutorService. See Tutorial.

 private class SmsSenderTask implement Runnable {
     private String text;
     private List<String> phoneNumbers;

     public void run() {
         for (String number : phoneNUmbers) {
             sendSms(number, text);
         }
     }
}

ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
for (Date d : dates) {
    long millis = d.getTime() - System.currentTimeMillis();
    service.schedule(new SmsSenderTask(text, phoneNumbers), millis, TimeUnit.MILLISECONDS);
}
like image 62
Maxim Tulupov Avatar answered Nov 18 '22 15:11

Maxim Tulupov


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 ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
    • See How to use ThreeTenABP….

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.

like image 1
Basil Bourque Avatar answered Nov 18 '22 14:11

Basil Bourque