如何使用 Google Cloud scheduler Python api 创建作业

How to create a job with Google Cloud scheduler Python api

我想创建一个 cron 作业,每天上午 10 点 运行 触发云函数。但是,我遇到了 Python api 的问题。当我创建一个工作时,它弹出这个错误。

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

这是我的代码:

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)

你试过吗:

from google.cloud.scheduler_v1.types import HttpTarget as Target


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": Target(uri: "https://us-central1-gerald-automl-test.cloudfunctions.net/automl-trainmodel-1-test-for-cron-job"),
     "schedule":"1 0 * * *",
     "time_zone":"utc+8",
     }
training_job= client.create_job(parent,job)

我还没有测试过这段代码,但很明显你正在将字符串发送到 http_target,并且它的实例需要是一个实际的 HttpTarget 对象,而不是只是一个字符串。

假设 utc+8 is Australia/Perthjob that will run every day at 10am is 0 10 * * * 那么函数应该是:

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)