如何获取 Firebase Scheduled Cloud Function 执行的时间?
How to get time when Firebase Scheduled Cloud Function executes?
我将任务存储在 firestore 中,其中包含时间戳、任务数据和一个名为 active 的布尔字段,默认情况下为 false。
假设我有 2 个任务,一个带有时间戳 11:15,一个带有时间戳 11:45。我预定的云功能每 15 分钟运行一次,并检查当时 firestore 中是否有任务。如果有任务,它会将 active 字段设置为 true。
我有一个每 15 分钟运行一次的云函数,它看起来像这样。
exports.scheduledFunction = functions.pubsub.schedule('*/15 * * * *').onRun((context) => {
return null;
});
我有几个问题。
如何获取预定函数执行的时间?比方说,如果那个时间是 10:30,我想在我的代码中引用那个时间,这样我就可以检查 firestore 中的值。
如何通过firestore查询是否有与scheduled function值相同的timestamp?
我是云函数的新手,所以任何建议或代码片段都会有所帮助。
How to get time when scheduled function is meant to be executed? If,
let's say, that time is 10:30 i want to have reference to that time in
my code so i can check with values in firestore.
应该使用context
对象的timestamp
属性,如下:
exports.scheduledFunction = functions.pubsub.schedule('*/15 * * * *').onRun((context) => {
const executionTimestamp = context.timestamp; // The timestamp at which the event happened.
return null;
});
How to query through Firestore and check if there is timestamp with
same value as scheduled function?
这取决于您在 Firestore 数据库中存储时间戳的方式。如果您在查询中使用标准 Firestore Date type, you can use a Firestore Timestamp
对象,如下所示:
admin // Using the Admin SDK since this code is to be used in a Cloud Function
.firestore()
.collection('collection')
.where('timestampField', '==', admin.firestore.Timestamp.fromDate(new Date(...)))
.get()
.then((snapshot) => {
snapshot.forEach((doc) => {
// ....
});
});
请注意,您可以在查询中很好地使用 >
、<=
、>=
和 >
运算符。
我将任务存储在 firestore 中,其中包含时间戳、任务数据和一个名为 active 的布尔字段,默认情况下为 false。
假设我有 2 个任务,一个带有时间戳 11:15,一个带有时间戳 11:45。我预定的云功能每 15 分钟运行一次,并检查当时 firestore 中是否有任务。如果有任务,它会将 active 字段设置为 true。
我有一个每 15 分钟运行一次的云函数,它看起来像这样。
exports.scheduledFunction = functions.pubsub.schedule('*/15 * * * *').onRun((context) => {
return null;
});
我有几个问题。
如何获取预定函数执行的时间?比方说,如果那个时间是 10:30,我想在我的代码中引用那个时间,这样我就可以检查 firestore 中的值。
如何通过firestore查询是否有与scheduled function值相同的timestamp?
我是云函数的新手,所以任何建议或代码片段都会有所帮助。
How to get time when scheduled function is meant to be executed? If, let's say, that time is 10:30 i want to have reference to that time in my code so i can check with values in firestore.
应该使用context
对象的timestamp
属性,如下:
exports.scheduledFunction = functions.pubsub.schedule('*/15 * * * *').onRun((context) => {
const executionTimestamp = context.timestamp; // The timestamp at which the event happened.
return null;
});
How to query through Firestore and check if there is timestamp with same value as scheduled function?
这取决于您在 Firestore 数据库中存储时间戳的方式。如果您在查询中使用标准 Firestore Date type, you can use a Firestore Timestamp
对象,如下所示:
admin // Using the Admin SDK since this code is to be used in a Cloud Function
.firestore()
.collection('collection')
.where('timestampField', '==', admin.firestore.Timestamp.fromDate(new Date(...)))
.get()
.then((snapshot) => {
snapshot.forEach((doc) => {
// ....
});
});
请注意,您可以在查询中很好地使用 >
、<=
、>=
和 >
运算符。