【问题标题】:Adding Timeout to Asynchronous Calls in Java在 Java 中为异步调用添加超时
【发布时间】:2014-05-27 01:07:53
【问题描述】:

不仅仅是一个 Firebase 问题,而是我正在使用 Firebase 从 Android 向后端发布帖子并运行 10 次,每秒一次。

Firebase ref = new Firebase(URL);
ref.child("Time").setValue(Currentime());

但是,这是一个异步调用,当我放置一个 while 循环时:

while (time_now < time_start + 10 seconds) {
     Firebase ref = new Firebase(URL);
     ref.child("Time").setValue(Currentime());
}

似乎先运行 while 循环,然后在最后运行约 10 个 Firebase 调用。有没有办法添加超时,以便在调用下一个异步调用之前强制异步 (Firebase) 调用运行一秒钟?

【问题讨论】:

  • 你能澄清一下你在找什么吗?具体来说,您是说循环非常快速地连续运行大约 10 次(例如,在一秒钟内)并且您希望它们以一秒钟的间隔更慢地启动?

标签: java android asynchronous firebase


【解决方案1】:

如果您查看Java example on the Firebase web site,您会发现它有一个doTransactions 方法和一个onComplete 方法:

Firebase countRef = new Firebase(URL);
Transaction.Handler handler = new Transaction.Handler() {
    @Override
    public Transaction.Result doTransaction(MutableData currentData) {
        // set the new time
        ...
    }

    @Override
    public void onComplete(FirebaseError error, boolean committed, DataSnapshot currentData) {
        if (error != null) {
            ...
        } else {
            if (!committed) {
                ...
            } else {
                // transaction committed, do next iteration
                ...
            }
            ...
        }
    }
});
countRef.runTransaction(handler);

所以你可以在doTransaction 方法中设置新时间:

// set the new time
currentData.setValue(time_now);
return Transaction.success(currentData);

然后在onComplete 方法中开始下一次迭代。

// transaction committed, do next iteration
if (time_now < time_start + 10 seconds) {
    countRef.runTransaction(handler);
}

【讨论】:

    猜你喜欢
    • 2021-03-25
    • 2018-05-27
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 2017-07-10
    相关资源
    最近更新 更多