A function run infinitely in Servlet

Asked

Viewed 72 times

0

I have a Servlet application that constantly receives POST requests, I do the data processing and processing normally in its due Java classes, however one of my applications it should not be rotated when there is a request and yes to each time period set (ex: 1 hour).

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

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

  • 1

    You can schedule execution (search for "schedule"). In Spring-boot, there is the annotation @Schedule (or something like that) that you can put in a method that it will execute as it is configured in the annotation. No need for external requisition or to start.

1 answer

1


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

Running something when the application initializes:

Create a Library:

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 Istener to be recognized you can use the web.xml:

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

Or use the annotation @WebListener:

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

This article and the very Javadoc explain the functioning of ServletContextListener.

Perform tasks periodically:

Create a ScheduledExecutorService and schedule tasks with an interval:

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, the Runnable myTask will run every 2 minutes, with an initial delay of 1 minute. That is, after 1 minute this block runs, the message will be displayed Hello world on the console every two minutes.

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

  • scheduleAtFixedRate executes "always" in the specified range.
  • scheduleWithFixedDelay will run after the end of the last run + the interval

This article and the own Javadoc explain the functioning of ScheduledExecutorService.

Putting it all together:

Now just join the two concepts and schedule tasks as soon as the application is initialized:

@WebListener
public class ExampleContextListener implements ServletContextListener {

  @Override
  public void contextInitialized(ServletContextEvent event) {
    scheduleMyTask();
  }

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

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

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

  //...
}

Note: Some frameworks may offer their own mechanisms for this. The ideal is to read your documentation if you use them.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.