There is a service that must be run periodically. How best to implement a periodic assignment in Java? What are the pros and cons of using Thread.sleep, TimerTask and a trappool?

package main; import services.Service; public class Main { public static void main(String[] args) { Service s = new Service(); while (true) { s.service(); try { Thread.sleep(5000); } catch (InterruptedException e) { } } } } 
  • decipher the "service" and its context - is it JavaEE, Android, Play! Framework or something else? in this case, the answer strongly depends on the context and there is no universal recipe. Even Thread.sleep, despite all its flaws, may be the most acceptable in some cases. - Ramiz
  • @Ramiz, this is JavaEE, a service that works with MongoDB and Postgres - typemoon
  • Does it make sense to keep such a service in mind? Maybe some cron-th cause the desired jarku? - Serhii Dikobrazko

1 answer 1

When developing application software, you should always strive to use abstractions of the highest possible level, especially if it is an enterprise application. I don’t know what exactly you mean by "JavaEE service", but the EJB container provides the infrastructure for both thread management and periodic tasks. Use @Schedule and @Timeout instead of Thread.sleep() , TimerTask and the like.

 @Singleton public class TimerBean { @Schedule(second = "*/5", minute = "*", hour = "*", persistent = false) public void periodicTask() throws InterruptedException { ... } } 
  • Yes, @Shedule is an excellent solution, but instead of all these parameters you can use cron @Scheduled right away (cron = "* / 5 * * * * *"). - Andrii Torzhkov