如何使用Java中的计时器在特定时间内运行作业?

编程入门 行业动态 更新时间:2024-10-14 06:25:20
本文介绍了如何使用Java中的计时器在特定时间内运行作业?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在开发一个Web应用程序,我需要运行一个60秒的线程,需要检查来自Web服务的响应。如果响应在60秒内到达,我将转发成功,然后我将在60秒后转发到超时页面。我在使用JSF 2.0? 我曾想过使用定时器,但不确定我是否只能在短时间内运行定时器。

I am developing a web application where I need to run a thread for 60 seconds which needs to check for response coming from a webservice. If the response arrives within 60 seconds I will forward to success othewise I will forward to a time out page after 60 seconds. I am using JSF 2.0? I have thought of using the Timer but not sure whenther I can run the timer for sprcefic amount of time only.

这有什么智能解决方案吗? ?

Is there any smart solution for this ??

推荐答案

绝对不使用计时器为此!对于一次性运行的桌面应用程序来说很有趣,但是在长期运行的Java EE Web应用程序中使用它时会遇到严重的潜在问题。

Do absolutely not use Timer for this! It's funny for one-time-run desktop applications, but it has severe potential problems when used in a lifetime long running Java EE web application.

而是使用来自 java.util .concurrent 包。这是一个启动示例:

Rather use the executors from the java.util.concurrent package. Here's a kickoff example:

ExecutorService executor = Executors.newSingleThreadExecutor(); // An application wide thread pool executor is better. Callable<InputStream> task = new Callable<InputStream>() { @Override public InputStream call() throws Exception { // Do here your webservice call job. return new URL("stackoverflow").openStream(); } }; try { InputStream input = executor.invokeAny(Arrays.asList(task), 60, TimeUnit.SECONDS); // Successful! Forward to success page here. } catch (TimeoutException e) { // Timeout occurred. Forward to timeout page here. }

更多推荐

如何使用Java中的计时器在特定时间内运行作业?

本文发布于:2023-11-27 13:32:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638281.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:作业   计时器   时间内   如何使用   在特定

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!