Search code examples
pythonpython-3.xgoogle-cloud-platformgoogle-cloud-scheduler

How to create a job with Google Cloud scheduler Python api


I would like to create a cron job that will run every day at 10am to trigger a cloud function. However, I am having a problem with the Python api. When I create a job it pops out this error.

TypeError: Parameter to MergeFrom() must be instance of same class: expected google.cloud.scheduler.v1.HttpTarget got str.

Here is my code:

from google.cloud import scheduler_v1

project_id = XXXX
client = scheduler_v1.CloudSchedulerClient.from_service_account_json(
    r"./xxxx.json")

parent= client.location_path(project_id,'us-central1')
job={"name":"traing_for_model",
     "description":"this is for testing training model",
     "http_target":"https://us-central1-xxxx-test.cloudfunctions.net/automl-trainmodel-1-test-for-cron-job",
     "schedule":"1 0 * * *",
     "time_zone":"utc+8",
     }
training_job= client.create_job(parent,job)

Solution

  • Assuming utc+8 is Australia/Perth and job that will run every day at 10am is 0 10 * * * then the function should be:

    from google.cloud import scheduler_v1
    
    project_id = XXXX
    client = scheduler_v1.CloudSchedulerClient.from_service_account_json(
        r"./xxxx.json")
    
    parent= client.location_path(project_id,'us-central1')
    
    job={"name":"projects/your-project/locations/app-engine-location/jobs/traing_for_model",
         "description":"this is for testing training model",
         "http_target": {"uri":"https://us-central1-gerald-automl-test.cloudfunctions.net/automl-trainmodel-1-test-for-cron-job"},
         "schedule":"0 10 * * *",
         "time_zone":"Australia/Perth",
         }
    
    training_job= client.create_job(parent,job)