安排函数运行时间


如果您要安排函数在指定时间运行,可使用 firebase-functions/v2/scheduler 提供的 onSchedule 处理程序。这些函数使用 Cloud Scheduler 按您定义的时间或间隔调用函数逻辑。

准备工作

虽然需要结算,但总费用应是可控的,因为每项 Cloud Scheduler 作业每月费用为 0.10 美元,并且每个 Google 账号可以享受三项免费作业的福利。您可使用 Blaze 价格计算器根据您的预计使用情况来估算费用。

您必须为您的项目启用 Cloud Scheduler API。对于大多数 Firebase 项目而言,该 API 应该已启用;您可以在 Google Cloud 控制台中验证该 API 是否已启用。

编写预定函数

Cloud Functions for Firebase 中,预定逻辑位于您的函数代码中,没有特殊的部署时间要求。例如,如需每天清理非活跃用户账号一次,您可以编写一个以下面的导入语句开头的函数:

Node.js

// The Cloud Functions for Firebase SDK to set up triggers and logging.
const {onSchedule} = require("firebase-functions/v2/scheduler");
const {logger} = require("firebase-functions");

// The Firebase Admin SDK to delete inactive users.
const admin = require("firebase-admin");
admin.initializeApp();

// The es6-promise-pool to limit the concurrency of promises.
const PromisePool = require("es6-promise-pool").default;
// Maximum concurrent account deletions.
const MAX_CONCURRENT = 3;

Python

# The Cloud Functions for Firebase SDK to set up triggers and logging.
from firebase_functions import scheduler_fn

# The Firebase Admin SDK to delete users.
import firebase_admin
from firebase_admin import auth

firebase_admin.initialize_app()

然后,您可以使用 onSchedule 启动 Cloud Scheduler 任务:

Node.js

// Run once a day at midnight, to clean up the users
// Manually run the task here https://console.cloud.google.com/cloudscheduler
exports.accountcleanup = onSchedule("every day 00:00", async (event) => {
  // Fetch all user details.
  const inactiveUsers = await getInactiveUsers();

  // Use a pool so that we delete maximum `MAX_CONCURRENT` users in parallel.
  const promisePool = new PromisePool(
      () => deleteInactiveUser(inactiveUsers),
      MAX_CONCURRENT,
  );
  await promisePool.start();

  logger.log("User cleanup finished");
});

Python

# Run once a day at midnight, to clean up inactive users.
# Manually run the task here https://console.cloud.google.com/cloudscheduler
@scheduler_fn.on_schedule(schedule="every day 00:00")
def accountcleanup(event: scheduler_fn.ScheduledEvent) -> None:
    """Delete users who've been inactive for 30 days or more."""
    user_page: auth.ListUsersPage | None = auth.list_users()
    while user_page is not None:
        inactive_uids = [
            user.uid for user in user_page.users if is_inactive(user, timedelta(days=30))
        ]
        auth.delete_users(inactive_uids)
        user_page = user_page.get_next_page()

Cloud Scheduler 支持 Unix Crontab 和 App Engine 语法。例如,如需使用 Crontab,您可以使用如下代码:

Node.js

exports.scheduledFunctionCrontab = onSchedule("5 11 * * *", async (event) => {
  // ...
});

Python

@scheduler_fn.on_schedule(schedule="5 11 * * *")

部署预定函数

在您部署预定函数时,系统会自动创建调度器作业和 HTTP 函数。Firebase CLI 会回显函数名称;您可以在 Google Cloud 控制台中查看作业和函数。系统会根据以下惯例为主题命名:

firebase-schedule-function_name-region

例如:

firebase-schedule-accountcleanup-us-east1.

在预定时间,默认计算服务账号会调用关联的 HTTP 函数。这意味着,只有关联的 Cloud Scheduler 作业才有权运行该函数。