以固定速率安排 Callable

发布于 2024-12-03 05:42:57 字数 378 浏览 1 评论 0原文

我有一个任务想要以固定速率运行。但是我还需要每次执行后任务的结果。这是我尝试过的:

任务

class ScheduledWork implements Callable<String>
{
    public String call()
    {
        //do the task and return the result as a String
    }
}

否 我尝试使用 ScheduledExecutorService 来安排它。事实证明,您无法以固定速率安排 Callable,只有 Runnable 可以这样做。

请指教。

I have a task that I want to run at a fixed rate. However I also need the result of the task after each execution. Here is what I tried:

The task

class ScheduledWork implements Callable<String>
{
    public String call()
    {
        //do the task and return the result as a String
    }
}

No I tried to use the ScheduledExecutorService to scheduled it. Turns out you cannot schedule a Callable at a fixed rate, only a Runnable can be done so.

Please advise.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

子栖 2024-12-10 05:42:57

使用生产者/消费者模式:拥有可运行其结果放在 BlockingQueue。有另一个线程 take( ) 从队列中。

Take 是一个阻塞调用(即仅当队列中有内容时才返回),因此您将在结果可用时立即获得结果。

您可以将其与 好莱坞模式 结合起来,为等待线程提供回调,以便您的代码被调用当有东西可用时。

Use a producer/consumer pattern: Have the Runnable put its result on a BlockingQueue. Have another thread take() from the queue.

Take is a blocking call (ie only returns when something is on the queue), so you'll get your results as soon as they're available.

You could combine this with the hollywood pattern to provide the waiting thread with a callback so your code gets called when something is available.

风流物 2024-12-10 05:42:57

除非您不关心 Callable 的返回值,否则您可以将其包装在 Runnable 中,并使用它传递给 ScheduledExecutorService

public static Runnable runnableOf(final Callable<?> callable)
{
    return new Runnable()
    {
        public void run()
        {
            try
            {
                callable.call();
            }
            catch (Exception e)
            {
            }
        }
    };
}

然后,当您想要提交到 ScheduledExecutroService 时,您可以传递您的 Callable

ses.scheduleAtFixedRate(runnableOf(callabale), initialDelay, delay, unit);

Unless if you don't care about the return value of your Callable, you can wrap it in a Runnable and use that to pass to ScheduledExecutorService.

public static Runnable runnableOf(final Callable<?> callable)
{
    return new Runnable()
    {
        public void run()
        {
            try
            {
                callable.call();
            }
            catch (Exception e)
            {
            }
        }
    };
}

Then when you want to submit to ScheduledExecutroService you can pass your Callable:

ses.scheduleAtFixedRate(runnableOf(callabale), initialDelay, delay, unit);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文