'How to send out many different notifications on specific dates?

What is the easiest way to send notifications on a specific date in Java? I don't need to just send one - I have a list where I can add items and give them a specific date and time. So all of the items have a separate time that I need a notification to be sent out on.

Later on I might also need to be able to stop a notification from going out if I delete an item from the list or have a notification's date be changed if I change the date of the according item in the list. But first I just need to get the notification part working.



Solution 1:[1]

The best bet for this is Firebase Cloud Messaging . The reason is that you can control when and what to send via a dashboard in your Firebase Console.

If you want to do it without a system like Firebase you would need a custom backend implementation.

Medium Article on Implementing Firebase Cloud Messaging Push Notifications

Solution 2:[2]

ScheduledExecutorService

The Executors framework can execute a task after a certain amount of time elapses. Use ScheduledExecutorService class.

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor() ;

Be sure to eventually shut down your executor service. Otherwise its backing pool of threads may continue running indefinitely, like a zombie ????.

Calculate the amount of time to wait.

LocalDate ld = LocalDate.of( 2022 , Month.FEBRUARY, 23 ) ;
LocalTime lt = LocalTime.of( 15 , 30 ) ;
ZoneId z = ZoneId.of( "America/Edmonton" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Instant instant = zdt.toInstant() ;
Duration d = Duration.between( Instant.now() , instant ) ;

Define your task as a Runnable or a Callable. Submit to the scheduled executor service with a delay.

Future future = ses.schedule( task , d.toSeconds() , TimeUnit.SECONDS ) ;

Track each returned Future object to query if the task is done, or to cancel the task.

Repeat this scheduling for each task in your list.

The scheduled executor service is not persisted. So if you care to pick up where things stood at the time your app last ran, you’ll need to do the persistence yourself to record what tasks are not yet done.

All of this has been covered many times already on Stack Overflow. So search to learn more.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Narendra_Nath
Solution 2