What are the benefits of using ScheduledExecutorService
's scheduleAtFixedRate()
to run a piece of code on a regular basis instead of creating a new Runnable
that has a forever loop coupled with a Thread.sleep()
that causes the thread to sleep for the desired period?
Is there a performance gain with one of the methods?
The biggest benefit of using
ScheduledExecutorService
is that you don't need to write the code, and that it is well tested. It does also have support for cancelling tasks out of the box, and you can schedule more than one task.Another benefit is that other developers know what the
ScheduledExecutorService
does, they can read the javadoc, and they can ask questions about it on puplic forums, and get help, while it's harder to get help for custom code.The javadoc for ScheduledExecutorService does also have a good example of how to create a tasks that executes every 10 seconds for an hour, and then gets cancelled.