Pirai Sudie
Pirai Sudie

Reputation: 172

Run task periodically in Java using java.util.TimerTask

While scheduling tasks using java.util.TimerTask how i can make sure that run method will execute only after current execution is completed, otherwise tasks queue size will keep growing and eventually task will be executing always. i am beginner and looking help

Upvotes: 0

Views: 554

Answers (2)

prasad_
prasad_

Reputation: 14287

Use a java.util.Timer with the TimerTask. One of these timer's two methods can be used:

  • schedule(TimerTask task, long delay, long period)

  • scheduleAtFixedRate(TimerTask task, long delay, long period)

Where:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.

Also, refer this article: What is the difference between schedule and scheduleAtFixedRate?

Upvotes: 1

Wim Deblauwe
Wim Deblauwe

Reputation: 26848

Use ExecutorService#scheduleWithFixedDelay(). This will start the 'delay' when the current task finishes (as opposed to scheduleAtFixedRate())

Upvotes: 1

Related Questions