简体   繁体   English

如何在没有页面请求的情况下自动调用servlet / class /方法?

[英]how to automatically call a servlet/class/method without page request?

We have a page that calls a servlet every minute. 我们有一个每分钟都调用一个servlet的页面。 This servlet connects to another website to get some data, process this data, then sends the response through the response.getWriter() method. 此servlet连接到另一个网站以获取一些数据,处理此数据,然后通过response.getWriter()方法发送响应。

If there are two different users accessing the page at the same time, two requests would be made to the same servlet. 如果有两个不同的用户同时访问该页面,则会向同一个servlet发出两个请求。 Though there is still only one instance of the servlet, there would be two processes (perhaps on two different threads) that would try to connect to the other website. 尽管仍然只有一个servlet实例,但是会有两个进程(可能在两个不同的线程上)尝试连接到另一个网站。

What we want is to have another class/method/servlet that would connect to the other website, process the data, then save it to cache/session. 我们想要的是拥有另一个连接到其他网站的类/方法/ servlet,处理数据,然后将其保存到缓存/会话。 This class/method/servlet has to be invoke/called every minute so that when the first servlet is called from the page, it would just get the data from the cache/session and not try to connect to the website. 这个类/方法/ servlet必须每分钟调用/调用,这样当从页面调用第一个servlet时,它只会从缓存/会话中获取数据,而不是尝试连接到网站。 How do we implement this? 我们如何实现这个? (problem is how the new class/method/servlet would be invoke/called automatically every minute without having to make a request from a page) (问题是如何在不必从页面发出请求的情况下每分钟自动调用/调用新类/方法/ servlet)

Create a scheduled task that reads external web page(Use Jsoup for easier access) and reads the data into a synchronized Map and from Servlet you can just read that Map from application scope 创建一个读取外部Web页面的计划任务(使用Jsoup以便于访问)并将数据读入synchronized Map ,从Servlet中您可以从应用程序范围读取该Map

getServletContext().getAttribute("dataMap");

and read the data from it 并从中读取数据

您必须创建一个计划任务来完成此任务,此计划任务的间隔将为1分钟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM