简体   繁体   中英

Run Google Cloud Function at a specific time

I'd like to schedule the execution of a Cloud Function to a specific time. It should be run only once.

After X seconds (the time is passed to the startTask function), the "finishTask" function should be called.

Google Cloud does not have service that will do what you need that I am aware of. If you need X to happen N seconds after user does Y, you will need to code that service yourself.

You do not specify what services you are using for compute (App Engine, Compute Engine, Kubernetes, etc.) but writing a task secheduling service in just about any language is not very hard. There are many ways to accomplish this (client side code / server side code). Many OS / language combinations support scheduling a function with a timeout and callback.

A possible workaround could be to:

  • Create a cron job that will trigger when you want
  • Trigger action
  • Delete the cron job

The easiest way is to create a pub/sub topic, cron-topic that your cloud function subscribes to. Cloud Scheduler can push an event to cron-topic on a schedule

Create the Topic & Subscription

gcloud pubsub topics create cron-topic
# create cron-sub for testing.  Function will create it's own subscription
gcloud pubsub subscriptions create cron-sub --topic cron-topic

Create the Schedule

Command is below, but since it's beta, see the console guide here

# send a message every 3 hours. For testing use `0/2 * * * *` for every 2 min
gcloud beta scheduler jobs create pubsub --topic=cron-topic --schedule='0 */3 * * *'

Create a Function to Consume the cron-topic Topic

Put your function code in the current directory and use this command to deploy the function listening to the cron-topic topic

FUNCTION_NAME=cron-topic-listener
gcloud functions deploy ${FUNCTION_NAME} --runtime go111 --trigger-topic cron-topic

note pub/sub events are sent at least once. In some cases the event can be sent more than once. Make sure your function is idempotent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM