如何获取 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;
  });

我有几个问题。

我是云函数的新手,所以任何建议或代码片段都会有所帮助。

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) => {
          // ....
      });
    });

请注意,您可以在查询中很好地使用 ><=>=> 运算符。