A function rotate endlessly in the Servlet

0

I have a servlet application that constantly receives POST requests, I do data processing and processing normally in its proper Java classes, but one of my applications it should not be run when there is a request, but every time of defined time (eg 1 hour).

That is, regardless of whether or not there are calls in the servlet, each time period that function must be called and its code executed.

How would this be done in a Java Web Servlet application?

    
asked by anonymous 11.01.2018 / 06:08

1 answer

1

You can use ServletContextListener together with ScheduledExecutorService . The ServletContextListener will be called when your application is initialized and finalized. ScheduledExecutorService will execute tasks repeatedly.

Running something when the application is initialized:

Create a listener:

package com.example;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ExampleContextListener implements ServletContextListener {

  @Override
  public void contextInitialized(ServletContextEvent servletContextEvent) {
    System.out.println("Contexto inicializado!");
  }

  @Override
  public void contextDestroyed(ServletContextEvent servletContextEvent) {
    System.out.println("Contexto destruido!");
  }
}

For the listener to be recognized you can use web.xml :

<listener>  
    <listener-class>
        com.example.ExampleContextListener
    </listener-class>
</listener>

Or use the @WebListener annotation:

@WebListener
public class ExampleContextListener implements ServletContextListener {  
    // ...
}

This article is itself Javadoc explain the operation of ServletContextListener .

Perform tasks periodically:

Create a ScheduledExecutorService and schedule tasks with a range:

public void scheduleMyTask() {
  ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

  Runnable myTask = new Runnable() {
    public void run() {
      System.out.println("Hello world");
    }
  };

  ScheduledFuture scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(myTask, 1, 2, TimeUnit.MINUTES);
}

In this example, Runnable myTask will run every 2 minutes, with an initial delay of 1 minute. That is, after 1 minute of that block is executed, the message Hello world in the console will be displayed every two minutes.

You should consider whether the method that best fits your use case is scheduleAtFixedRate or scheduleWithFixedDelay . The difference between them is:

  • scheduleAtFixedRate executes "always" in the specified range.
  • scheduleWithFixedDelay will execute after the last execution ends + the interval

This article and the

11.01.2018 / 14:11