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