Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
405 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...