如何在指定的时间间隔定期自动调用servlet [英] How can I automatically invoke a servlet periodically at specified time intervals

查看:82
本文介绍了如何在指定的时间间隔定期自动调用servlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

必须定期调用servlet.(例如andorid中的服务概念)

Have to call the servlet periodically.(like service concept in andorid)

如何执行此操作.使用计时器或其他解决方案?

How to do this. Using timer or any other solution?

谢谢.

推荐答案

要扩展JB Nizet的评论…

To expand on the comments by JB Nizet…

以前被接受的答案是一种hack.如果目标是要在您的Web应用程序中执行一些常规任务,那么Java提供了一些巧妙的技术来实现这一目标.

The formerly accepted answer is kind of a hack. If the goal is to get some regular task to be performed as part of your web app, Java provides a couple of slick technologies to make this happen.

第一个是Servlet规范定义的挂钩,用于在部署Web应用程序和关闭Web应用程序时调用代码.该挂钩是 ServletContextListener .

The first is a hook defined by the Servlet spec to have code invoked when a web app is deployed and when a web app is shutting down. This hook is the ServletContextListener.

第二部分是executor服务,它被添加到Java的最新版本中,作为旧Timer类的更复杂的替代品.特别是,您需要 ScheduledExecutorService

The second piece is the executor service added to recent versions of Java as a more sophisticated alternative to the old Timer class. In particular you need the ScheduledExecutorService.

因此,当您的Web应用程序启动时,ServletContextListener将启动ScheduledExecutorService.当ServletContextListener通知关闭时,它告诉执行程序正常退出.

So when your web app start up, the ServletContextListener launches a ScheduledExecutorService. When the ServletContextListener is informed of a shutdown, it tells the executor to gracefully quit.

一个窍门:确保在执行程序中捕获所有所有异常.如果有异常泄漏,则执行程序将静默停止执行.这是一个功能,而不是错误.阅读文档并进行一些谷歌搜索.

One trick to this: Be sure to capture all exceptions in your executor. If an exception leaks, the executor silently stops executing. This is a feature not a bug. Read the doc and study up with some googling.

在StackOverflow中搜索示例和这两个示例的讨论.

Search StackOverflow for examples and discussion of both of these.

这篇关于如何在指定的时间间隔定期自动调用servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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