Search code examples
javatimerconcurrencysingletonejb

Java @Singleton EJB executing method at most every 5 seconds


Hi I am implementing a web application with email sending functionality. In order for our email server not to be blacklisted we have to send at most one email per 5 seconds. So I was thinking to create an @Singleton EJB Email sender, in that way only one EJB instance will be responsible for sending all the emails in whole application. How should I implement the 5 seconds counter in order to send at most 1 email per 5 seconds? e.g the class will look like that

  @Singleton
  public class EmailSender {
       public void sendEmail(String msg){
                 ....
       }
  }

Solution

  • Try using @Schedule:

    @Singleton
    public class EmailSender {
         Queue<Email> queue;
    
         @Schedule(second = "*/5", minute = "*", hour = "*")
         public void sendEmail(String msg){
              if (!queue.isEmpty()) {
                   //get queue element and send email
              }
         }
    }