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

sam picture sam · Apr 8, 2017 · Viewed 9.2k times · Source

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 ?

Answer

Maxim Tulupov picture Maxim Tulupov · Apr 8, 2017

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