If you want to have an event fire at some predetermined moment, but you want the user-interface of the app to remain responsive to the user’s actions, then you need a background thread. You should almost never sleep the GUI thread of your app, as that makes your app unresponsive and appear to be crashed. For fun, try it the wrong way: Drop a Thread.sleep
call into your GUI code to see how it temporarily freezes your app.
Learn about concurrency. Start with the Oracle Tutorial, and work your way up to eventually making an annual read of the Bible, Java Concurrency in Practice by Goetz et al.
The Executors framework was built to make threading easier. Specifically, you will want the ScheduledExecutorService
class. This has been covered many many times already on Stack Overflow. Search to learn more.
And learn about how to properly interact with the GUI thread from a background thread.
Never use LocalDateTime
to track a moment, as explained in the class doc. For a moment, use Instant
, OffsetDateTime
, or ZonedDateTime
. For a span-of-time on the scale of hours-minutes-seconds, use Duration
. The Duration
class offers methods such as toMinutes
, toSeconds
, the results of which you can feed as your delay to a ScheduledExecutorService
. All of these classes have been covered many many times on Stack Overflow. Search to learn more.