Skip to content

Run a java function after a specific number of seconds

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.



new java.util.Timer().schedule( 
        new java.util.TimerTask() {
            public void run() {
                // your code here


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.

User contributions licensed under: CC BY-SA
3 People found this is helpful