Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to schedule a task in Tomcat

Tags:

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.

like image 954
dileepVikram Avatar asked Aug 14 '13 07:08

dileepVikram


People also ask

How do I schedule a task on a server?

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.

How do you schedule a task in Java?

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.

How do I schedule a run command?

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.


1 Answers

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 :)

like image 129
Benjamin Leconte Avatar answered Sep 28 '22 05:09

Benjamin Leconte