如何使用Java中的计时器在特定时间内运行作业? [英] How to use the timer in Java to run a Job for a specific amount of time?

查看:120
本文介绍了如何使用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.

而是使用来自<的执行程序a href =http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html\"rel =nofollow> 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("http://stackoverflow.com").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中的计时器在特定时间内运行作业?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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