虽然需要结算,但总费用应是可控的,因为每项 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.constadmin=require("firebase-admin");admin.initializeApp();// The es6-promise-pool to limit the concurrency of promises.constPromisePool=require("es6-promise-pool").default;// Maximum concurrent account deletions.constMAX_CONCURRENT=3;
# The Cloud Functions for Firebase SDK to set up triggers and logging.fromfirebase_functionsimportscheduler_fn# The Firebase Admin SDK to delete users.importfirebase_adminfromfirebase_adminimportauthfirebase_admin.initialize_app()
// Run once a day at midnight, to clean up the users// Manually run the task here https://console.cloud.google.com/cloudschedulerexports.accountcleanup=onSchedule("every day 00:00",async(event)=>{// Fetch all user details.constinactiveUsers=awaitgetInactiveUsers();// Use a pool so that we delete maximum `MAX_CONCURRENT` users in parallel.constpromisePool=newPromisePool(()=>deleteInactiveUser(inactiveUsers),MAX_CONCURRENT,);awaitpromisePool.start();logger.log("User cleanup finished");});
# 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")defaccountcleanup(event:scheduler_fn.ScheduledEvent)-> None:"""Delete users who've been inactive for 30 days or more."""user_page:auth.ListUsersPage|None=auth.list_users()whileuser_pageisnotNone:inactive_uids=[user.uidforuserinuser_page.usersifis_inactive(user,timedelta(days=30))]auth.delete_users(inactive_uids)user_page=user_page.get_next_page()
[null,null,["最后更新时间 (UTC):2025-08-17。"],[],[],null,["\u003cbr /\u003e\n\n2nd gen 1st gen \n\n\u003cbr /\u003e\n\nIf you want to schedule functions to run at specified times, use\nthe `onSchedule` handler to create a\n[Pub/Sub](https://cloud.google.com/pubsub/) topic that uses\n[Cloud Scheduler](https://cloud.google.com/scheduler/) to trigger events on\nthat topic.\n\nBefore you begin\n\nTo use this solution in your Firebase project, your project must be on the\nBlaze pricing plan. If it's not already on the Blaze plan,\n[upgrade your pricing plan](/pricing).\n\nThough billing is required, you can expect the overall cost to be manageable, as\neach Cloud Scheduler job costs $0.10 (USD) per month, and there is an\nallowance of three jobs per Google account, at no charge. Use the Blaze\n[pricing calculator](/pricing#blaze-calculator) to generate a cost estimate\nbased on your projected usage.\n\nThe Pub/Sub and Cloud Scheduler APIs must be enabled for your\nproject. These should already be enabled for most Firebase projects; you can\nverify in the [Google Cloud console](https://console.cloud.google.com/).\n| **Important:** Cloud Scheduler used to require that your project have a [Google App Engine app](https://cloud.google.com/appengine/docs/). During its setup you were prompted to select a location, and this location became your project's [*location for\n| default Google Cloud resources*](/docs/projects/locations#default-cloud-location) (Cloud Scheduler being one of these resources). This location is used for resources in your project that have an association with App Engine, including your *default* Cloud Firestore database instance and your *default* Cloud Storage bucket (specifically with the name format `*.appspot.com`).\n|\n| However, now that Cloud Scheduler and recently provisioned\n| default Cloud Storage buckets (with the name format\n| `*.firebasestorage.app`) no longer have a dependency\n| on App Engine, you only need to consider this location if you're using\n| 1st gen scheduled functions and `*.appspot.com`\n| buckets.\n\nWrite a scheduled function\n\nIn Cloud Functions for Firebase, scheduling logic resides in your functions code,\nwith no special deploy-time requirements. To create a scheduled function,\nuse `functions.pubsub.schedule('your schedule').onRun((context))`.\nFor example, to run a function every\nfive minutes with\n[App Engine cron.yaml](https://cloud.google.com/appengine/docs/standard/python/config/cronref)\nsyntax, do something like this: \n\n exports.scheduledFunction = functions.pubsub.schedule('every 5 minutes').onRun((context) =\u003e {\n console.log('This will be run every 5 minutes!');\n return null;\n });\n\nBoth Unix Crontab and App Engine syntax\nare supported by Cloud Scheduler. For example, to use Crontab to select a\nspecific timezone in which to run a scheduled function, do something like this: \n\n exports.scheduledFunctionCrontab = functions.pubsub.schedule('5 11 * * *')\n .timeZone('America/New_York') // Users can choose timezone - default is America/Los_Angeles\n .onRun((context) =\u003e {\n console.log('This will be run every day at 11:05 AM Eastern!');\n return null;\n });\n\nThe value for `timeZone` must be a time zone name from the\n[tz database](http://en.wikipedia.org/wiki/Tz_database). See the\n[Cloud Scheduler reference](https://cloud.google.com/scheduler/docs/reference/rpc/google.cloud.scheduler.v1#job)\nfor more information on supported properties.\n| **Important:** Depending on how you design your scheduling logic, a function may be triggered multiple times, with the next instance running while the previous instance is still executing.\n\nDeploy a scheduled function\n\nWhen you deploy a scheduled function, the related scheduler job and pub/sub\ntopic are created automatically. The Firebase CLI echoes the topic name,\nand you can view the job and topic in the\n[Google Cloud console](https://console.cloud.google.com/project/_/cloudscheduler).\nThe topic is named according to the following convention:\n\n**firebase-scheduled-\u003cvar translate=\"no\"\u003efunction_name\u003c/var\u003e-\u003cvar translate=\"no\"\u003eregion\u003c/var\u003e**\n\nFor example:\n\n**firebase-scheduled-scheduledFunctionCrontab-us-east1.**\n| **Important:** Make sure you do not manually delete or modify the topic or scheduler job in the console. Doing this could cause errors in the execution of your scheduled function."]]