42

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

Manuel Selva
  • 18,554
  • 22
  • 89
  • 134

4 Answers4

94

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);
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
cletus
  • 616,129
  • 168
  • 910
  • 942
  • 6
    what if I close main window of application? will this task be still running? – Tomasz Mularczyk Apr 19 '15 at 11:39
  • 1
    Yes. It would still be running, since it is opening a new thread and running it standalone. You've to make sure you shutdown the scheduler. This can be done by (from Cletus example): exec.shutdown(); A side note, shutdown() doesn't shutdown immediately. It just states; it no longer accepts incomming requests. Therefore, it could potentially run "forever", if a thread doesn't stop executing. To avoid this, you set a timeout for the shutdown - !exec.awaitTermination(3, TimeUnit.SECONDS); - and if it took more than 3 seconds to shutdown, then - exec.shutdownNow(); – Alexander Falk Jul 27 '18 at 09:13
  • 2
    In Java 8 you can use lambda expression for instance of Runnable: `ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); exec.scheduleAtFixedRate(() -> { //do stuff }, 1, 1, TimeUnit.SECONDS);` – Anton Ermakov Oct 11 '18 at 13:54
8

By using a ScheduledExecutorService.

Have a look at Executors.newScheduledThreadPool. It will allow you to created a ScheduledExecutorService which lets you submit Runnables to be executed at regular intervals.

Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
developmentalinsanity
  • 6,109
  • 2
  • 22
  • 18
7
while (true) {
    thread.sleep(1000)
    method();
}

In many cases there will be better alternatives. But this is the easiest way to implement a regular execution of your method() at an interval of 1000ms + n (where n is the amount of time spent executing method())

Of course instead of 1000, you can put any millisecond value you desire. It could also be an idea to implement the while loop on a flag that another thread controls; so that there is an way to stop execution of the loop without having to kill the program.

flamming_python
  • 690
  • 7
  • 13
  • 3
    almost - it will be at least 1000. It depends when the thread scheduler decides to start running the thread again. It will be 1000 + a + n (where a is the time it takes the scheduler to activate the thread again) – RNJ Oct 25 '12 at 09:46
5

Use below code :

Timer timer = new Timer(); 
timer.schedule( new TimerTask() 
{ 
    public void run() { 
    // do your work 
    } 
}, 0, 60*(1000*1));
Lucifer
  • 29,392
  • 25
  • 90
  • 143