首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Servlet程序即服务

Servlet程序即服务
EN

Stack Overflow用户
提问于 2009-03-16 13:23:20
回答 4查看 220关注 0票数 0

我有一个Java servlet程序,它会在tomcat启动时启动。我已经提到过程序在启动时加载。我没有使用任何HTTP请求或响应。

我需要的是我需要运行的程序作为一个服务,或需要有自动刷新在一定的时间间隔。如何做到这一点?谁能帮帮我!

谢谢你,戈帕尔。

EN

回答 4

Stack Overflow用户

发布于 2009-03-16 15:51:42

Quartz是一个很好的想法,但根据您的需要,可能有点夸大其词。我认为你真正的问题是试图将你的服务塞进servlet,而你实际上并没有监听传入的HttpServletRequests。相反,考虑使用ServletContextListener来启动您的服务,并使用计时器,如莫里斯所建议的:

web.xml:

代码语言:javascript
复制
<listener>
    <listener-class>com.myCompany.MyListener</listener-class>
</listener>

然后你的类看起来是这样的:

代码语言:javascript
复制
public class MyListener implements ServletContextListener {

    /** the interval to wait per service call - 1 minute */
    private static final int INTERVAL = 60 * 60 * 1000;

    /** the interval to wait before starting up the service - 10 seconds */
    private static final int STARTUP_WAIT = 10 * 1000;

    private MyService service = new MyService();
    private Timer myTimer;

    public void contextDestroyed(ServletContextEvent sce) {
        service.shutdown();
        if (myTimer != null)
            myTimer.cancel();
    }

    public void contextInitialized(ServletContextEvent sce) {
        myTimer = new Timer();
        myTimer.schedule(new TimerTask() {
            public void run() {
                myService.provideSomething();
            }
        },STARTUP_WAIT, INTERVAL
      );
    }
}
票数 3
EN

Stack Overflow用户

发布于 2009-03-16 13:44:27

我建议您使用Quartz。您可以使用quartz定义一个计划的作业。

代码语言:javascript
复制
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzTest {
   public static void main(String[] args) {
     try {
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler.start();

        scheduler.shutdown();
      } catch (SchedulerException se) {
        se.printStackTrace();
      }
  }
}
票数 1
EN

Stack Overflow用户

发布于 2009-03-16 13:26:38

每次.war文件更改时,tomcat都会自动刷新

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/650405

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档