I have a specific function that I want to be executed after 5 seconds. How can i do that in Java?
I found javax.swing.timer, but I can't really understand how to use it. It looks like I'm looking for something way simpler then this class provides.
Please add a simple usage example.
The easiest way to delay a java program is by using Thread. sleep() method. The sleep() method is present in the Thread class. It simply pauses the current thread to sleep for a specific time.
A Java. util. Timer is a utility class used to schedule a task to be executed after a specific amount of time. Tasks can be scheduled for one-time execution or for repeated execution periodically.
Timer and TimerTask are java util classes that we use to schedule tasks in a background thread. Basically, TimerTask is the task to perform, and Timer is the scheduler.
new java.util.Timer().schedule( new java.util.TimerTask() { @Override public void run() { // your code here } }, 5000 );
EDIT:
javadoc says:
After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection). However, this can take arbitrarily long to occur.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With