How to automatically run my java function periodically when the Apache tomcat server is started?
function, java, jsp, setinterval, tomcat
Solution
You can write a ServletContextListener that uses a `ScheduledExecutorService` (or `Timer`) to start your process in the `contextInitialized` method and stops it in the `contextDestroyed` method.
It could look something like this:
private volatile ScheduledExecutorService executor;
public void contextInitialized(ServletContextEvent sce)
{
executor = Executors.newScheduledThreadPool(2);
executor.scheduleAtFixedRate(myRunnable, 0, 3, TimeUnit.MINUTES);
}
public void contextDestroyed(ServletContextEvent sce)
{
final ScheduledExecutorService executor = this.executor;
if (executor != null)
{
executor.shutdown();
this.executor = null;
}
}
Problem
I have a java function which checks and modify values in my SQL database to avoid errors, i need it to be executed automatically on server startup as well as on restart. i created a jsp page to call this function as jsp support "setInterval" in which i can run it automatically after every 3 minutes to remove errors from my database now i need it to be executed automatically on server startup. can anyone guide me on this? the following is my jsp code: ``` setInterval(function(){Autolf();},60000); function Autolf() { $.post('autolgfn.jsp', { abc:1 }, function(response,status,xhr) { alert(response.trim()); }); } ``` the above code calls function from a java page which is connected to database. please help me to run it automatically on server startup and keep running after every 3 minutes. thanks in advance