Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Thread every X seconds

Tags:

java

What is the easiest way to have a piece of Java code scheduled at a given rate ?

like image 411
Manuel Selva Avatar asked Aug 22 '10 13:08

Manuel Selva


People also ask

How do I stop scheduled executor service?

Learn to cancel a task submitted to an executor service if the task still has to be executed and/or has not been completed yet. We can use the cancel() method of Future object that allows making the cancellation requests.

How do you create a wait method in Java?

wait() causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0). The current thread must own this object's monitor.


1 Answers

In Java 5+ with a ScheduledExecutorService:

ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); exec.scheduleAtFixedRate(new Runnable() {   @Override   public void run() {     // do stuff   } }, 0, 5, TimeUnit.SECONDS); 

The above method is favoured. Prior to Java 5 you used Timer and TimerTask:

timer.scheduleAtFixedRate(new TimerTask() {   @Override   public void run() {     // do staff   } }, 0, 5000); 
like image 135
cletus Avatar answered Oct 13 '22 20:10

cletus