Background streams
You must have a background thread and wait for the next email. Java 5 adds some classes to make such background threads and tasks pretty easy.
Some other answers mentioned a quartz library. I have not used this, and it may have nice features. But this is certainly not necessary for your purpose. Classes built into Java are enough.
ServletContextListener
Create a subclass of ServletContextListener . This class must be called before processing any servlet request. So this is the place to initialize the objects used by your web application. This class is also called when your web application closes.
ScheduledExecutorService
In your servlet context listener, when your web application starts, create a ScheduledExecutorService . This class uses a thread pool to run tasks in the background. You specify the initial delay before the first run (optional) and indicate how often to repeat the task.
In your servlet context listener, be sure to turn off your ScheduledExecutorService when your web application shuts down. If you do not, the background threads in the pool will continue to live. The java process running on your host operating system to start your servlet container will continue rather than exit.
Be sure to add try-catch around your task. Any exception that reaches your ScheduledExecutorService causes the service to silently stop. See this funny post (cautious, mischievous language).
Search StackOverflow for more details and examples. This question is basically a duplicate, so I saved this report.
source share