java: run a function after a specific number of seconds

Viewed 295469

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.

12 Answers
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.

Something like this:

// When your program starts up
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

// then, when you want to schedule a task
Runnable task = ....    
executor.schedule(task, 5, TimeUnit.SECONDS);

// and finally, when your program wants to exit
executor.shutdown();

There are various other factory methods on Executor which you can use instead, if you want more threads in the pool.

And remember, it's important to shutdown the executor when you've finished. The shutdown() method will cleanly shut down the thread pool when the last task has completed, and will block until this happens. shutdownNow() will terminate the thread pool immediately.

Your original question mentions the "Swing Timer". If in fact your question is related to SWing, then you should be using the Swing Timer and NOT the util.Timer.

Read the section from the Swing tutorial on "How to Use Timers" for more information.

you could use the Thread.Sleep() function

Thread.sleep(4000);
myfunction();

Your function will execute after 4 seconds. However this might pause the entire program...

I think in this case :

import javax.swing.*;
import java.awt.event.ActionListener;

is the best. When the Question is prevent Ui stack or a progress not visible before a heavy work or network call. We can use the following methods (from my experience) :

Run a method after one Second :

 public static void startMethodAfterOneSeconds(Runnable runnable) {
        Timer timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent e) {
                runnable.run();
            }

        });
        timer.setRepeats(false); // Only execute once
        timer.start(); 
    }

Run a method after n second once, Non repeating :

public static void startMethodAfterNMilliseconds(Runnable runnable, int milliSeconds) {
    Timer timer = new Timer(milliSeconds, new ActionListener() {
        @Override
        public void actionPerformed(java.awt.event.ActionEvent e) {
            runnable.run();
        }

    });
    timer.setRepeats(false); // Only execute once
    timer.start(); 
}

Run a method after n seconds, and repeat :

 public static void repeatMethodAfterNMilliseconds(Runnable runnable, int milliSeconds) {
        Timer timer = new Timer(milliSeconds, new ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent e) {
                runnable.run();
            }

        });
        timer.setRepeats(true); // Only execute once
        timer.start(); 
    }

And the Usage :

 startMethodAfterNMilliseconds(new Runnable() {
            @Override
            public void run() {
                // myMethod(); // Your method goes here. 
            }
        }, 1000);

Perhaps the most transparent way is to use the postDelayed function of the Handler class the following way:

new Handler().postDelayed(this::function, 1000);

or you can implement the function inside, for example:

new Handler().postDelayed(() -> System.out.println("A second later"), 1000);

Where the first argument is the function, the second argument is the delay time in milliseconds. In the first example, the name of the called function is "function".

Related