如何使用 Google Cloud 调度程序 Python api 创建作业

Posted

技术标签:

【中文标题】如何使用 Google Cloud 调度程序 Python api 创建作业【英文标题】:How to create a job with Google Cloud scheduler Python api 【发布时间】:2020-06-26 03:08:55 【问题描述】:

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

TypeError:MergeFrom() 的参数必须是同一类的实例:预期的 google.cloud.scheduler.v1.HttpTarget 得到了 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)

【问题讨论】:

【参考方案1】:

你有没有尝试过:

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 对象,而不仅仅是一个字符串。

【讨论】:

【参考方案2】:

假设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)

【讨论】:

感谢您的评论,我能够创造这份工作:)。 如果我的回答对您有所帮助,请将其标记为已接受,以便为社区提高知名度。 您能告诉我为什么作业名称是完整路径吗?

以上是关于如何使用 Google Cloud 调度程序 Python api 创建作业的主要内容,如果未能解决你的问题,请参考以下文章

在 Google Cloud Logs 中看不到应用程序日志

如何为 Google Cloud Scheduler 设置基本身份验证

如何验证来自 HTTP 请求的 Google Cloud Task 令牌?

验证来自 Google Cloud Scheduler 的 HTTP 请求

__init__.py 中的 google.cloud 命名空间导入错误

如何在 Spring Cloud Data Flow 中为 Spring Batch 作业设置调度程序?