Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: run a function after a specific number of seconds

Tags:

java

timer

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.

like image 823
ufk Avatar asked Feb 13 '10 15:02

ufk


People also ask

How do you delay a method in Java?

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.

Can you set a Timer in Java?

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.

What is TimerTask in Java?

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.


1 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.

like image 87
tangens Avatar answered Nov 15 '22 22:11

tangens