How to start the background method of working with fixed intervals?

I am using JSP / Servlet on Apache Tomcat. I have to run the method every 10 minutes. How can I achieve this?

+5
source share
2 answers

Since you are on Tomcat, which is just a barebones servletcontainer, you cannot use EJB @Schedulefor this, which is recommended by the Java EE specification. It is best to choose ScheduledExecutorServicefrom the Java 1.5 package java.util.concurrent. You can call this with ServletContextListener, as shown below:

@WebListener
public class BackgroundJobManager implements ServletContextListener {

    private ScheduledExecutorService scheduler;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new SomeTask(), 0, 10, TimeUnit.MINUTES);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        scheduler.shutdownNow();
    }

}

where the class is SomeTaskas follows:

public class SomeTask implements Runnable {

    @Override
    public void run() {
        // Do your job here.
    }

}

Java EE EJB em (, Glassfish, JBoss AS, TomEE ..), @Singleton EJB @Schedule. , . , , EJB:

@Singleton
public class SomeTask {

    @Schedule(hour="*", minute="*/10", second="0", persistent=false)
    public void run() {
        // Do your job here.
    }

} 

, , , (@PersistenceContext ..), ScheduledExecutorService — // , barebones servletcontainer, Tomcat.

, Timer "" - Java EE. , Java EE ( Java Concurrency ):

  • Timer , ScheduledExecutorService .
  • Timer , . ScheduledExecutorService .
  • , TimerTask, , Timer , .. ( ). ScheduledThreadExecutor , , . , , , .
+10

ScheduledExecutorService, ServletContextListener

public class MyContext implements ServletContextListener 
{
    private ScheduledExecutorService sched;

    @Override
    public void contextInitialized(ServletContextEvent event) 
    {
        sched = Executors.newSingleThreadScheduledExecutor();
        sched.scheduleAtFixedRate(new MyTask(), 0, 10, TimeUnit.MINUTES);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) 
    {
        sched.shutdownNow();
    }
}

, Java Timer ServletContextListener, Java EE, Thread . ( ScheduledExecutorService - ).

Timer timer = new Timer("MyTimer");
MyTask t = new MyTask();

//Second Parameter is the specified the Starting Time for your timer in
//MilliSeconds or Date

//Third Parameter is the specified the Period between consecutive
//calling for the method.

timer.schedule(t, 0, 1000*60*10);

MyTask, TimerTask, , Runnable, :

class MyTask extends TimerTask 
{
  public void run() 
  { 
    // your code here
  }
}
+3

All Articles