I have a web application deployed in Tomcat. I have a set of code in it, that checks database for certain data and then sends a mail to users depending on that data. Can somebody suggest how to schedule this in Tomcat.
Schedule the TaskClick Start, point to Control Panel, then point to Scheduled Tasks, and then click Add Scheduled Task. The Scheduled Task Wizard appears. Click Next. A list of programs that are available on your computer is displayed.
One of the methods in the Timer class is the void schedule(Timertask task, Date time) method. This method schedules the specified task for execution at the specified time. If the time is in the past, it schedules the task for immediate execution.
Regardless of the Windows version or edition you have, you can also use the Run window to launch the Task Scheduler. Press the Windows + R keys on your keyboard to open Run, and then type taskschd. msc in the Open field. Finally, click or tap on OK, or press Enter on your keyboard.
Actually, the best way to schedule task in Tomcat is to use ScheduledExecutorService. TimeTask should not be used in J2E applications, this is not a good practice.
Example with the right way :
create a package different that you controller one (servlet package), and create a new java class on this new package as example :
// your package import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; @WebListener public class BackgroundJobManager implements ServletContextListener { private ScheduledExecutorService scheduler; @Override public void contextInitialized(ServletContextEvent event) { scheduler = Executors.newSingleThreadScheduledExecutor(); // scheduler.scheduleAtFixedRate(new DailyJob(), 0, 1, TimeUnit.DAYS); scheduler.scheduleAtFixedRate(new HourlyJob(), 0, 1, TimeUnit.HOURS); //scheduler.scheduleAtFixedRate(new MinJob(), 0, 1, TimeUnit.MINUTES); // scheduler.scheduleAtFixedRate(new SecJob(), 0, 15, TimeUnit.SECONDS); } @Override public void contextDestroyed(ServletContextEvent event) { scheduler.shutdownNow(); } }
After that you can create other java class (one per schedule) as follow :
public class HourlyJob implements Runnable { @Override public void run() { // Do your hourly job here. System.out.println("Job trigged by scheduler"); } }
Enjoy :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With