从其他方法的await()返回

发布于 2024-12-07 14:11:37 字数 577 浏览 1 评论 0原文

我是 Play 新手!我有一个关于 HTTP 异步编程的问题。 我有一段这样的代码:

public void someMethod() {
    for (int i = 0; i < 100; i++) {
        doSomething();
        await(someTime);
    }
}

用户通过发送 GET/POST 请求来调用此方法。 它会进行一些计算(doSomething()),然后等待一段时间。 但是:用户必须能够从 await(someTime) 中“返回”,并且循环应继续下一次迭代,而无需等待所有 “someTime” 时间。

示例代码:

public void nextAwait() {
    continueАForLoop();
}

用户通过 GET/POST 调用 nextAwait() 方法。 如果调用它,循环将继续,并且 doSomething() 将(必须)立即调用!

那么,在 Play 中可以吗?

预先感谢您的回答:)

I’m newbie in Play! and I have one question about asynchronous programming in HTTP.
I have a piece of code like this:

public void someMethod() {
    for (int i = 0; i < 100; i++) {
        doSomething();
        await(someTime);
    }
}

This method is invoked by user by sending GET/POST request.
It does some computations (doSomething()) and after that it waits some time.
But: the user has to have ability to “return” from await(someTime) and the loop should continue next iteration without waiting all the “someTime” time.

The example code:

public void nextAwait() {
    continueАForLoop();
}

The user invokes nextAwait() method by GET/POST.
If it is invoked, the loop will continue and doSomething() will be (has to be) invoked immediately!

So, is it possible in Play?

Thanks in advance for answers :)

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

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

发布评论

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

评论(2

烟沫凡尘 2024-12-14 14:11:37

对此的简单答案是等待较短的时间,然后检查用户交互的某些值,然后继续等待。

例如,假设您的总等待时间为 10 秒,

public void someMethod() {
    for (int i = 0; i < 100; i++) {
        doSomething();
        for (int j=0; j<10; j++) {
            if (!userInterrupt) await("1s");
        }
    }
}

因此,这会将您的等待时间分解为 1 秒的块,并检查一个值以查看用户是否中断了等待。这意味着用户在处理被释放之前最多等待1秒。

The simple answer to this, is to wait for a shorter period of time, then check some value for user interaction, and then continue waiting.

for example, let's assume your total wait time is 10 seconds

public void someMethod() {
    for (int i = 0; i < 100; i++) {
        doSomething();
        for (int j=0; j<10; j++) {
            if (!userInterrupt) await("1s");
        }
    }
}

So, this breaks your wait down to 1 second chunks, and checks a value to see if the user has interrupted the wait. It means that the user will wait a maximum of 1 second before the processing is released.

北城孤痞 2024-12-14 14:11:37

我不知道它是否以这种方式工作,但您可以尝试类似的方法:(您在某处有一个字段监视器 = new Object() )

synchronized ( this.monitor ) {
  this.monitor.wait( someTime );
}

并在您调用的其他方法中:

synchronized ( monitor ) {
  this.monitor.notifyAll();
}

I don't know if it works this way but you could try something like that: (You have a field monitor = new Object() somewhere)

synchronized ( this.monitor ) {
  this.monitor.wait( someTime );
}

and in the other method you call:

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