如何在Apache tomcat服务器启动时定期自动运行我的java函数?

jas*_*sim 2 java jsp tomcat function setinterval

我有一个java函数,它检查和修改我的SQL数据库中的值以避免错误,我需要它在服务器启动时以及重新启动时自动执行.我创建了一个jsp页面来调用这个函数作为jsp支持"setInterval",我可以在每3分钟后自动运行它以从我的数据库中删除错误,现在我需要它在服务器启动时自动执行.任何人都可以指导我吗?

以下是我的jsp代码:

setInterval(function(){Autolf();},60000);

function Autolf()
{

$.post('autolgfn.jsp',
        {
    abc:1
        },
        function(response,status,xhr)
        {
            alert(response.trim());

        });

}
Run Code Online (Sandbox Code Playgroud)

上面的代码从连接到数据库的java页面调用函数.请帮我在服务器启动时自动运行它,并在每3分钟后继续运行.提前致谢

Bre*_*ken 7

您可以编写一个ServletContextListener,它使用ScheduledExecutorService(或Timer)在contextInitialized方法中启动您的进程并在方法中停止它contextDestroyed.

它可能看起来像这样:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)