Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinction between ScheduledExecutorService and rolling your own Runnable with Thread.sleep()

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?

like image 940
A Timmes Avatar asked Feb 24 '23 01:02

A Timmes


1 Answers

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.

like image 84
Kaj Avatar answered Apr 07 '23 01:04

Kaj