Skip to content
Advertisement

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.

Advertisement

Answer

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.

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