As Tomcat is a simple servletcontainer which does not offer builtin scheduling facilities, nor supports the very handy EJB @Schedule
annotation, you'd need to manage the scheduling yourself, or to use a 3rd party library such as Quartz, or to just delegate the job to the underlying operating system platform's scheduling facilities like Task Scheduler in Windows based platforms and Cron in Unix based platforms.
When using the standard APIs, you can use a ServletContextListener
to initialize the scheduler on startup and you can use ScheduledExecutorService
as scheduler.
Here's a kickoff example:
@WebListener
public class Config implements ServletContextListener {
private ScheduledExecutorService scheduler;
@Override
public void contextInitialized(ServletContextEvent event) {
long secondsUntilNoon = calculateItSomehow();
long secondsPerDay = 60 * 60 * 24;
scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new Mailer(), secondsUntilNoon, secondsPerDay, TimeUnit.SECONDS);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
scheduler.shutdownNow();
}
}
Where the Mailer
class just look like this:
public class Mailer implements Runnable {
@Override
public void run() {
// Do your mailing job here.
}
}
See also: