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

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

问题描述

我希望每隔6小时从订阅中检索并将订阅源存储到DB。我想在后台有一个计时器线程来完成这个任务。

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.

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

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

推荐答案

首先,我不会使用JSP。它不适用于。

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

当您使用Java EE 5时,请使用容器提供的jobscheduling API。更多细节取决于您正在使用的容器。例如,JBoss AS 5随附了Quartz。或者当您在JSP / Servlet上使用提供jobscheduling API的框架时,例如 Spring ,那么你应该使用它。

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.

如果没有(例如你正在使用)只是Tomcat 6),或者你想独立于容器和/或框架,创建一个 ServletContextListener ,带有 ScheduledExecutorService 。有关详细信息,请参阅此答案

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.

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

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.

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

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);

UpdateSubscriptions 必须实现 Runnable 并且实际工作需要在 run() @Override ,如链接答案中的示例所示。

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天全站免登陆