能否通过Google Cloud Scheduler Python SDK添加自定义标签并过滤任务?
使用Google Cloud Python SDK为Cloud Scheduler任务添加自定义标签
创建任务时添加自定义标签
创建新的Cloud Scheduler任务时,可直接在Job对象的labels参数中传入键值对形式的自定义标签:
from google.cloud import scheduler_v1 def create_scheduled_job_with_labels(project_id, location_id, job_id): client = scheduler_v1.CloudSchedulerClient() parent = f"projects/{project_id}/locations/{location_id}" # 构建HTTP目标示例,可根据实际场景调整为Pub/Sub等其他目标 http_target = scheduler_v1.HttpTarget( uri="https://example.com/your-endpoint", http_method=scheduler_v1.HttpMethod.POST ) # 定义自定义标签 job_labels = { "env": "production", "team": "backend", "task_type": "data_sync" } job = scheduler_v1.Job( name=f"{parent}/jobs/{job_id}", http_target=http_target, schedule="0 0 * * *", labels=job_labels ) response = client.create_job(request={"parent": parent, "job": job}) print(f"带标签任务创建完成: {response.name}")
为已有任务添加/更新自定义标签
针对已存在的任务,需先获取任务详情,更新labels字段后提交更新请求:
from google.cloud import scheduler_v1 def update_job_labels(project_id, location_id, job_id, new_labels): client = scheduler_v1.CloudSchedulerClient() job_name = f"projects/{project_id}/locations/{location_id}/jobs/{job_id}" # 获取当前任务信息 job = client.get_job(request={"name": job_name}) # 合并新标签(若需覆盖原有标签,直接赋值 job.labels = new_labels 即可) job.labels.update(new_labels) # 指定仅更新labels字段,避免修改其他任务配置 update_mask = scheduler_v1.FieldMask(paths=["labels"]) response = client.update_job(request={"job": job, "update_mask": update_mask}) print(f"任务标签更新成功: {response.labels}")
使用List API按标签过滤任务
添加标签后,调用List API时可通过filter参数指定标签过滤条件,语法为labels.<key>:<value>:
from google.cloud import scheduler_v1 def list_jobs_by_label(project_id, location_id, label_key, label_value): client = scheduler_v1.CloudSchedulerClient() parent = f"projects/{project_id}/locations/{location_id}" # 构建过滤条件 filter_str = f"labels.{label_key}:{label_value}" request = scheduler_v1.ListJobsRequest(parent=parent, filter=filter_str) page_result = client.list_jobs(request=request) print(f"匹配标签 {label_key}:{label_value} 的任务:") for job in page_result: print(f"- 任务名称: {job.name}, 标签: {job.labels}")
注意事项
- 标签键仅支持小写字母、数字、连字符、下划线和点,且不能以连字符或点开头/结尾
- 标签值可包含大小写字母、数字、连字符、下划线、点和空格,长度限制为63字符以内
内容的提问来源于stack exchange,提问作者mansi chauhan
相关产品推荐
相关产品推荐

