在服务器端为servlet JSP MVC网站运行定期任务 [英] running periodic task at server side for servlet JSP MVC website
问题描述
我使用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.
我想做以下事情:
- 清理一些数据每小时数据库
- 在某个XML文件中每15分钟生成并存储有关数据的统计信息
<问题是:目前我的所有代码都是从客户端收到的请求运行的。
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);
}
这两项任务可能如下所示:
where the both tasks can look like:
public class CleanDBTask extends TimerTask {
public void run() {
// Implement.
}
}
使用计时器$但是,不建议在Java EE中使用c $ c>。如果任务抛出异常,那么整个
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屋!