在服务器端为 servlet JSP MVC 网站运行定期任务 [英] running periodic task at server side for servlet JSP MVC website

查看:16
本文介绍了在服务器端为 servlet JSP MVC 网站运行定期任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 servlet 和 JSP 开发了一个 Web 应用程序.我本身没有使用任何框架,而是使用我自己自制的 MVC 框架.我使用 MySQL 作为后端.

I have developed a web application using using servlet and JSP. I am not using any framework per se, instead using my own home brewed MVC framework. I am using MySQL as a backend.

我想做以下事情:

  1. 每小时从数据库中清理一些数据
  2. 每 15 分钟生成一次有关数据的统计信息并将其存储在某个 XML 文件中

问题是:目前我所有的代码都是根据从客户端收到的请求而运行的.

The problem is: currently all my code runs as a result of the request received from a client.

如何在服务器端运行周期性任务?

How do I run periodic task(s) at the server side?

我现在的一个解决方案是在控制器的 init 函数中创建一个线程.还有其他选择吗?

One solution I have right now is to creare a thread in the controller's init function. Are there any other options?

推荐答案

您可以使用 ServletContextListener 在 webapp 启动时执行一些初始化.运行周期性任务的标准 Java API 方式是 定时器TimerTask.这是一个启动示例:

You can use ServletContextListener to execute some initialization on webapp's startup. The standard Java API way to run periodic tasks would be a combination of Timer and TimerTask. Here's a kickoff example:

public void contextInitialized(ServletContextEvent event) {
    Timer timer = new Timer(true);
    timer.scheduleAtFixedRate(new CleanDBTask(), 0, oneHourInMillis);
    timer.scheduleAtFixedRate(new StatisticsTask(), 0, oneQuartInMillis);
}

这两个任务的样子:

public class CleanDBTask extends TimerTask {
    public void run() {
        // Implement.
    }
}

在 Java EE 中不推荐使用 Timer.如果任务抛出异常,则整个 Timer 线程都会被杀死,您基本上需要重新启动整个服务器才能使其再次运行.Timer 对系统时钟的变化也很敏感.

Using Timer is however not recommended in Java EE. If the task throws an exception, then the entire Timer thread is killed and you'd basically need to restart the whole server to get it to run again. The Timer is also sensitive to changes in system clock.

更新更强大的java.util.concurrent 方式将是 ScheduledExecutorService 和一个 Runnable.这是一个启动示例:

The newer and more robust java.util.concurrent way would be a combination of ScheduledExecutorService and just a Runnable. Here's a kickoff example:

private ScheduledExecutorService scheduler;

public void contextInitialized(ServletContextEvent event) {
    scheduler = Executors.newSingleThreadScheduledExecutor();
    scheduler.scheduleAtFixedRate(new CleanDBTask(), 0, 1, TimeUnit.HOURS);
    scheduler.scheduleAtFixedRate(new StatisticsTask(), 0, 15, TimeUnit.MINUTES);
}

public void contextDestroyed(ServletContextEvent event) {
    scheduler.shutdownNow();
}

这篇关于在服务器端为 servlet JSP MVC 网站运行定期任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆