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

查看:23
本文介绍了如何以指定的时间间隔定期自动调用 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…

以前接受的答案有点像黑客.如果目标是让一些常规任务作为网络应用的一部分来执行,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.

第二部分是添加到 Java 最新版本中的 executor 服务,作为旧 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 被告知关闭时,它会告诉 executor 优雅地退出.

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