Search code examples
google-cloud-platformgoogle-cloud-scheduler

Cloud Scheduler randomness


I want to run a Cloud Function every day at a random time between 1 pm and 2 pm. I use Cloud Scheduler (cron) to publish a message to PubSub that is triggering the function. I want to make that randomness on the Cloud Scheduler side to avoid calling sleep in the function. Is there a way to achieve this?


Solution

  • You can't do that. You need an intermediary layer. The cheapest is to use Cloud Workflows.

    The power of Cloud Workflow is you pay only when you run a step, not on the workflow duration. Therefore you can sleep for a while, you won't pay for the idle CPU that you don't use, thing that happen when you use Cloud Functions or Cloud Run (when you put a SLEEP in your code).

    Here the process:

    • Create a step that call a URL that generate a random number. If you haven't a public URL that do that, you can use this sample with a Cloud Funcions
    • Create a following step that sleeps according to your random result of the previous step
    • Call your Cloud Function

    And you call your workflow with Cloud Scheduler on a daily basis