0

I want to make a background service in java and I have a function to periodically check the database. If there's no email to be sent it will sleep for a few minutes and if there's an email to be sent it will run the function and send the email to the user.

My question is, which approach should I use: Schedule or ExecutorService and what are the advantages if I use them.

Note Update*

  • I'm developing in JavaEE and use the JSF framework
mikej
  • 65,295
  • 17
  • 152
  • 131
Makku
  • 97
  • 1
  • 1
  • 10
  • We need more "context"... Is your application a Java EE or a Java SE edition application? This would change a lot. – Lorelorelore Jun 18 '18 at 08:09
  • @Lorelorelore I'm developing JavaEE and use JSF framework – Makku Jun 18 '18 at 08:14
  • Possible duplicate of [Timer vs. ScheduledExecutorService scheduling](https://stackoverflow.com/questions/48956511/timer-vs-scheduledexecutorservice-scheduling) – Capricorn Jun 18 '18 at 08:25

1 Answers1

0

If you are using Java EE then the @Schedule annotation should easily fit your needs. It is just simpler than managing the ExecutorService, and it does not requires any configuration in the application container.

@Schedules ({
   @Schedule(dayOfMonth="Last"),
   @Schedule(dayOfWeek="Fri", hour="23")
})
public void doPeriodicCheck() { ... }

As you can see, you can also combine more than one @Schedule, so to me it is also more flexible than ExecutorService.

Lorelorelore
  • 3,335
  • 8
  • 29
  • 40