JSP/Servlet Web 应用程序中的后台计时器任务 [英] Background timer task in JSP/Servlet web application

查看:37
本文介绍了JSP/Servlet Web 应用程序中的后台计时器任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在每 6 小时后从订阅中检索并从订阅中将提要存储到数据库.我想在后台有一个计时器线程来完成这个任务.

最好的方法是什么?普通的定时器线程还是 Quartz API?

解决方案

首先,我不会为此使用 JSP.它不是为了.

当您使用 Java EE 5 时,为此使用容器提供的作业调度 API.更多细节取决于您使用的容器.例如,JBoss AS 5 自带 Quartz.或者,当您在 JSP/Servlet 之上使用提供作业调度 API 的框架时,例如 Spring,那么你应该使用它.

如果没有(例如,您只使用 Tomcat 6),或者您想独立于容器和/或框架,请创建一个 ServletContextListener 带有 ScheduledExecutorService.在这个答案中可以找到更多详细信息.

或者当您已经在支持 EJB 3.1(JBoss AS 6、GlassFish 3,但不是 Tomcat 7)的 Java EE 6 容器上时,最简单的方法是创建一个 @Singleton 带有 @Schedule 方法.>

@Singleton公共类更新订阅{@Schedule(小时=*/6",分钟=0",秒=0",持久=假)公共无效运行(){//在这里做你的工作.}}

就是这样.无需进一步配置.

<小时>

更新:根据评论,您使用的是 Tomcat(6 还是 7?).要在每 6 小时运行一次任务的 webapp 启动期间启动一个线程,请使用 beforelinked answer 并在 scheduleAtFixedRate()方法

scheduler.scheduleAtFixedRate(new UpdateSubscriptions(), 0, 6, TimeUnit.HOURS);

UpdateSubscriptions 类必须实现 Runnable 和实际工作需要在run() 方法,你@Override,就像链接答案中的示例一样.>

I want to retrieve from subscription and store feeds to DB from subscription after every 6 hours. I want to have a timer thread in background to accomplish this task.

What's the best way? A normal timer thread or Quartz API?

解决方案

To start, I wouldn't use JSP for this. There it is not for.

When you're on Java EE 5, use the container-provided jobscheduling APIs for this. Further detail depends on the container you're using. JBoss AS 5 for example ships with Quartz out the box. Or when you're using a framework on top of JSP/Servlet which offers jobscheduling APIs, like as Spring, then you should use it.

If there are none (e.g. you're using just Tomcat 6), or you want to be independent from the container and/or framework, create a ServletContextListener with a ScheduledExecutorService. Further detail can be found in this answer.

Or when you're already on a Java EE 6 container which supports EJB 3.1 (JBoss AS 6, GlassFish 3, but thus not Tomcat 7), easiest is to create a @Singleton EJB with @Schedule method.

@Singleton
public class UpdateSubscriptions {

    @Schedule(hour="*/6", minute="0", second="0", persistent=false)
    public void run() {
        // Do your job here.
    }

}        

That's it. No further configuration is necessary.


Update: as per the comments, you're using Tomcat (6 or 7?). To start a thread during webapp's startup which runs the task every 6 hours, use the example as provided in the beforelinked answer and make the following change in the scheduleAtFixedRate() method

scheduler.scheduleAtFixedRate(new UpdateSubscriptions(), 0, 6, TimeUnit.HOURS);

The class UpdateSubscriptions must implement Runnable and the actual job needs to be done in the run() method which you @Override, like as in the example in the linked answer.

这篇关于JSP/Servlet Web 应用程序中的后台计时器任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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