【发布时间】:2020-06-01 20:30:17
【问题描述】:
试图找出these Background Processing methods 中哪一个适合我的情况。
案例:如何在应用程序在后台运行或关闭时更新 Firestore 上的字段?
简短说明:用户输入时间(毫秒),当该时间结束时,无论应用程序正在运行还是关闭,我都想更新 Firestore 中的字段,我目前有以下代码:
private void setTaskEndTime(long xEndTime) {
long mLeftTime = xEndTime - mCurrentTime;
new CountDownTimer(mLeftTime, 1000) {
@Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
@Override
public void onFinish() {
//HERE <===================
}
}.start();
}
我已经尝试过 Firebase Cloud Function;这样当时间结束时,它应该更新字段,但问题是云函数在更新字段(或至少我的代码)之前花费了太多时间:
const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
let db = admin.firestore();
exports.wtf = functions.region('europe-west1').firestore
.document('Users/{userId}/Tasks/{docId}')
.onUpdate((docSnapshot, context) => {
var mUserID = context.params.userId; //Document userID
var mDocID = context.params.docId; //Document taskID
var oldSnapshot = docSnapshot.before.data();
var oldCurrentStatus = oldSnapshot.taskCurrentStatus;
var newSnapshot = docSnapshot.after.data();
var newCurrentStatus = newSnapshot.taskCurrentStatus;
var tempTime = newSnapshot.temporaryTime;
let cityRef = db.collection('Users').doc(mUserID).collection('Tasks').doc(mDocID);
if (newCurrentStatus !== oldCurrentStatus && newCurrentStatus > 0) {
const myFunc = () => {
//Gets dd/MM/yyyy date and stores it in 'today'
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
let days = cityRef.update({
taskCompletedDays: admin.firestore.FieldValue.arrayUnion(today)
});
let hours = cityRef.update({
taskCompletedHours: admin.firestore.FieldValue.increment(tempTime)
});
let status = cityRef.update({ taskCurrentStatus: 0 });
}
setTimeout(myFunc, tempTime);
}
return true;
});
【问题讨论】:
标签: javascript java firebase google-cloud-firestore google-cloud-functions