查看招聘信息和任务

本文档介绍如何查看批量作业和任务。

准备工作

查看您的招聘信息

要查看作业,请选择以下方法之一:

查看您的任务列表

您可以使用 Google Cloud 控制台、gcloud CLI、Batch API、Go、Java、Node.js、Python 或 C++ 查看当前项目中的作业列表。

控制台

  1. 如需使用 Google Cloud 控制台查看当前项目中的作业列表,请转到作业列表页面。

    转到“作业”列表

    作业列表可能由多个页面组成。如果您需要继续访问下一页,请点击屏幕底部的 下一步

  2. 可选:如果要过滤作业列表,请点击 过滤条件。然后,输入或选择属性和值。

    例如,如需过滤列表以仅包含处于特定状态的作业,请输入以下内容:

    Status:JOB_STATE
    

    JOB_STATE 替换为作业状态,例如 FAILED

gcloud

查看所有作业

如需使用 gcloud CLI 查看当前项目中的作业列表,请使用 gcloud batch jobs list 命令

gcloud batch jobs list

查看过滤后的作业列表

(可选)您可以添加一个或多个标志以查看过滤后的作业列表:

  • 如需仅查看特定位置的作业,请添加 --location 标志。

  • 如需仅查看基于过滤条件表达式的作业,请指定 --filter 标志。

例如,使用以下命令:

gcloud batch jobs list \
    --location=LOCATION \
    --filter="FILTER_EXPRESSION"

替换以下内容:

  • LOCATION:一个或多个作业所在的位置

  • FILTER_EXPRESSION:用于定义您要列出的作业的过滤表达式。过滤器表达式必须定义一个或多个“属性-值”对,并用零个或多个布尔运算符(ANDORNOT分隔。

    例如,请参阅以下过滤表达式:

    • 根据作业状态进行过滤:如需仅查看处于特定状态的作业,请使用以下过滤表达式:

      status.state="JOB_STATE"
      

      JOB_STATE 替换为作业状态,例如 FAILED

    • 根据标签过滤:假设您的项目定义了以下自定义标签:

      • 为了在查看 Cloud Billing 报告时指示研究团队创建的作业及其资源,您的部分作业及其资源的 team 标签设置为 research

      • 为了指示具有时效性的工作负载,某些作业具有 deadline 标签,该标签设置为各种值。

      • 为了指明开发团队已成功测试的可运行对象,某些可运行对象具有设置为 truetested 标签。

      然后,您可以指定以下过滤表达式:

      (allocationPolicy.labels.team=research) AND ((labels.deadline:*) OR (runnables.labels.tested=true))
      

      此过滤表达式仅列出满足以下所有条件的作业:

      • 来自研究团队的作业,在作业分配政策上具有 team 标签,设置为 research

      • 至少满足以下条件之一的作业:

        • 具有时效性的作业,此类作业的 deadline 标签设置为任何值。

        • 至少有一个作业已成功完成测试的可运行对象,即至少具有一个 tested 标签设置为 true 的可运行对象的作业。

API

查看所有作业

如需使用 Batch API 查看当前项目中特定位置的作业列表,请向 jobs.list 方法发出 GET 请求。

GET https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/jobs

替换以下内容:

  • PROJECT_ID:当前项目的项目 ID

  • LOCATION:作业所在的位置

查看过滤后的作业列表

(可选)您可以指定 filter 查询参数,以查看基于过滤条件表达式的过滤后作业列表。

例如,发出以下 GET 请求:

GET https://batch.googleapis.com/v1/projects/example-project/locations/us-central1/jobs?filter=FILTER_EXPRESSION

FILTER_EXPRESSION 替换为使用网址编码过滤表达式。过滤器表达式必须定义一个或多个“属性-值”对,并用零个或多个布尔运算符(ANDORNOT分隔。

例如,请参阅以下过滤表达式:

  • 根据作业状态进行过滤:如需仅查看处于特定状态的作业,请使用以下过滤表达式:

    status.state="JOB_STATE"
    

    JOB_STATE 替换为作业状态,例如 FAILED

  • 根据标签过滤:假设您的项目定义了以下自定义标签:

    • 为了在查看 Cloud Billing 报告时指示研究团队创建的作业及其资源,您的部分作业及其资源的 team 标签设置为 research

    • 为了指示具有时效性的工作负载,某些作业具有 deadline 标签,该标签设置为各种值。

    • 为了指明开发团队已成功测试的可运行对象,某些可运行对象具有设置为 truetested 标签。

    然后,您可以指定以下过滤表达式:

    (allocationPolicy.labels.team%3Dresearch)%20AND%20((labels.deadline%3A*)%20OR%20(runnables.labels.tested%3Dtrue))
    

    此过滤表达式仅列出满足以下所有条件的作业:

    • 来自研究团队的作业,在作业分配政策上具有 team 标签,设置为 research

    • 至少满足以下条件之一的作业:

      • 具有时效性的作业,此类作业的 deadline 标签设置为任何值。

      • 至少有一个作业已成功完成测试的可运行对象,即至少具有一个 tested 标签设置为 true 的可运行对象的作业。

Go

Go

如需了解详情,请参阅 Batch Go API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

	batch "cloud.google.com/go/batch/apiv1"
	"cloud.google.com/go/batch/apiv1/batchpb"
	"google.golang.org/api/iterator"
)

// Lists all jobs in the given project and region
func listJobs(w io.Writer, projectID, region string) error {
	// projectID := "your_project_id"
	// region := "us-central1"

	ctx := context.Background()
	batchClient, err := batch.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer batchClient.Close()

	req := &batchpb.ListJobsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, region),
	}

	var jobs []*batchpb.Job
	it := batchClient.ListJobs(ctx, req)

	for {
		job, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("unable to list jobs: %w", err)
		}
		jobs = append(jobs, job)
	}

	fmt.Fprintf(w, "Jobs: %v\n", jobs)

	return nil
}

Java

Java

如需了解详情,请参阅 Batch Java API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.Job;
import java.io.IOException;

public class ListJobs {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";

    // Name of the region hosting the jobs.
    String region = "europe-central2";

    listJobs(projectId, region);
  }

  // Get a list of all jobs defined in given region.
  public static void listJobs(String projectId, String region) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `batchServiceClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (BatchServiceClient batchServiceClient = BatchServiceClient.create()) {

      // Construct the parent path of the job.
      String parent = String.format("projects/%s/locations/%s", projectId, region);

      for (Job job : batchServiceClient.listJobs(parent).iterateAll()) {
        System.out.println(job.getName());
      }
      System.out.println("Listed all batch jobs.");
    }
  }
}

Node.js

Node.js

如需了解详情,请参阅 Batch Node.js API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
/**
 * The region that hosts the job.
 */
// const region = 'us-central-1';

// Imports the Batch library
const batchLib = require('@google-cloud/batch');

// Instantiates a client
const batchClient = new batchLib.v1.BatchServiceClient();

async function callListJobs() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${region}`,
  };

  // Run request
  const iterable = await batchClient.listJobsAsync(request);
  for await (const response of iterable) {
    console.log(response);
  }
}

callListJobs();

Python

Python

如需了解详情,请参阅 Batch Python API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

from __future__ import annotations

from collections.abc import Iterable

from google.cloud import batch_v1

def list_jobs(project_id: str, region: str) -> Iterable[batch_v1.Job]:
    """
    Get a list of all jobs defined in given region.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        region: name of the region hosting the jobs.

    Returns:
        An iterable collection of Job object.
    """
    client = batch_v1.BatchServiceClient()

    return client.list_jobs(parent=f"projects/{project_id}/locations/{region}")

C++

C++

如需了解详情,请参阅 Batch C++ API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

#include "google/cloud/batch/v1/batch_client.h"

  [](std::string const& project_id, std::string const& location_id) {
    auto const parent = "projects/" + project_id + "/locations/" + location_id;
    // Initialize a client and issue the request.
    auto client = google::cloud::batch_v1::BatchServiceClient(
        google::cloud::batch_v1::MakeBatchServiceConnection());
    int i = 0;
    for (auto job : client.ListJobs(parent)) {
      if (!job) throw std::move(job).status();
      std::cout << "Job[" << i++ << "]  " << job->DebugString() << "\n";
    }
  }

查看任务详情

您可以使用 Google Cloud 控制台、gcloud CLI、Batch API、Go、Java、Node.js、Python 或 C++ 查看当前项目中作业的详细信息。

控制台

如需使用 Google Cloud 控制台查看当前项目中作业的详细信息,请按以下步骤操作:

  1. 在 Google Cloud 控制台中,前往作业列表页面。

    转到“作业”列表

  2. 作业名称列中,点击作业的名称。

    作业详情页面随即打开。

    详细信息标签页默认处于打开状态。如需了解详情,请点击其他标签页。

gcloud

如需使用 gcloud CLI 查看当前项目中作业的详细信息,请使用带有 --location 标志的 gcloud batch jobs describe 命令

gcloud batch jobs describe JOB_NAME \
    --location=LOCATION

替换以下内容:

  • JOB_NAME:现有作业的名称。

  • LOCATION:作业所在的位置

API

如需使用 Batch API 查看当前项目中作业的详细信息,请向 jobs.get 方法发出 GET 请求。

GET https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/jobs/JOB_NAME

替换以下内容:

  • PROJECT_ID:当前项目的项目 ID

  • LOCATION:作业所在的位置

  • JOB_NAME:现有作业的名称。

Go

Go

如需了解详情,请参阅 Batch Go API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

	batch "cloud.google.com/go/batch/apiv1"
	"cloud.google.com/go/batch/apiv1/batchpb"
)

// Retrieves the information about the specified job, most importantly its status
func getJob(w io.Writer, projectID, region, jobName string) (*batchpb.Job, error) {
	// projectID := "your_project_id"
	// region := "us-central1"
	// jobName := "some-job"

	ctx := context.Background()
	batchClient, err := batch.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewClient: %w", err)
	}
	defer batchClient.Close()

	req := &batchpb.GetJobRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/jobs/%s", projectID, region, jobName),
	}

	response, err := batchClient.GetJob(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("unable to get job: %w", err)
	}

	fmt.Fprintf(w, "Job info: %v\n", response)

	return response, nil
}

Java

Java

如需了解详情,请参阅 Batch Java API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.Job;
import com.google.cloud.batch.v1.JobName;
import java.io.IOException;

public class GetJob {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";

    // Name of the region hosts the job.
    String region = "europe-central2";

    // The name of the job you want to retrieve information about.
    String jobName = "JOB_NAME";

    getJob(projectId, region, jobName);
  }

  // Retrieve information about a Batch Job.
  public static void getJob(String projectId, String region, String jobName) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `batchServiceClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (BatchServiceClient batchServiceClient = BatchServiceClient.create()) {

      Job job =
          batchServiceClient.getJob(
              JobName.newBuilder()
                  .setProject(projectId)
                  .setLocation(region)
                  .setJob(jobName)
                  .build());

      System.out.printf("Retrieved the job: %s ", job.getName());
    }
  }
}

Node.js

Node.js

如需了解详情,请参阅 Batch Node.js API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
/**
 * The region that hosts the job.
 */
// const region = 'us-central-1';
/**
 * The name of the job you want to retrieve information about.
 */
// const jobName = 'YOUR_JOB_NAME';

// Imports the Batch library
const batchLib = require('@google-cloud/batch');

// Instantiates a client
const batchClient = new batchLib.v1.BatchServiceClient();

async function callGetJob() {
  // Construct request
  const request = {
    name: `projects/${projectId}/locations/${region}/jobs/${jobName}`,
  };

  // Run request
  const response = await batchClient.getJob(request);
  console.log(response);
}

callGetJob();

Python

Python

如需了解详情,请参阅 Batch Python API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


from google.cloud import batch_v1

def get_job(project_id: str, region: str, job_name: str) -> batch_v1.Job:
    """
    Retrieve information about a Batch Job.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        region: name of the region hosts the job.
        job_name: the name of the job you want to retrieve information about.

    Returns:
        A Job object representing the specified job.
    """
    client = batch_v1.BatchServiceClient()

    return client.get_job(
        name=f"projects/{project_id}/locations/{region}/jobs/{job_name}"
    )

C++

C++

如需了解详情,请参阅 Batch C++ API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

#include "google/cloud/batch/v1/batch_client.h"

  [](std::string const& project_id, std::string const& location_id,
     std::string const& job_id) {
    auto const name = "projects/" + project_id + "/locations/" + location_id +
                      "/jobs/" + job_id;
    // Initialize a client and issue the request.
    auto client = google::cloud::batch_v1::BatchServiceClient(
        google::cloud::batch_v1::MakeBatchServiceConnection());
    auto response = client.GetJob(name);
    if (!response) throw std::move(response).status();
    std::cout << "GetJob() succeeded with " << response->DebugString() << "\n";
  }

查看任务

要查看某个作业的任务,请选择以下方法之一:

查看作业的任务列表

您可以使用 Google Cloud 控制台、gcloud CLI、Batch API、Go、Java、Node.js、Python 或 C++ 查看作业或作业任务组中的任务列表。

如果要过滤作业或作业任务组中的任务列表(例如,仅列出已成功运行的任务),您必须使用 gcloud CLI 或 Batch API。

控制台

如需使用 Google Cloud 控制台查看作业的任务摘要,请查看作业的详细信息,打开作业详情页面。然后,查看任务详情部分。

gcloud

如需使用 gcloud CLI 查看作业任务组中的任务列表,请使用带有以下标志的 gcloud batch tasks list 命令

gcloud batch tasks list \
    --job=JOB_NAME \
    --location=LOCATION

替换以下内容:

  • JOB_NAME:现有作业的名称。

  • LOCATION:作业所在的位置

或者,您可以添加 --filter 标志,以根据过滤表达式查看作业任务组中经过过滤的任务列表。

例如,使用以下命令:

gcloud batch tasks list \
    --job=example-job \
    --location=us-central1 \
    --filter="FILTER_EXPRESSION"

FILTER_EXPRESSION 替换为过滤器表达式

例如,您可以指定以下过滤表达式,以仅查看作业的任务组中正在运行或已成功运行的任务:

STATE=RUNNING OR STATE=SUCCEEDED

API

如需使用 Batch API 查看作业任务组中的任务列表,请向 tasks.list 方法发出 GET 请求:

GET https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/jobs/JOB_NAME/taskGroups/TASK_GROUP_NAME/tasks

替换以下内容:

  • PROJECT_ID:当前项目的项目 ID

  • LOCATION:作业所在的位置

  • JOB_NAME:现有作业的名称。

  • TASK_GROUP_NAME:要查看其详细信息的任务组的名称。该值必须设置为 group0

或者,您可以指定 filter 查询参数,以根据过滤表达式查看作业任务组中经过过滤的任务列表。

例如,发出以下 GET 请求:

GET https://batch.googleapis.com/v1/projects/example-project/locations/us-central1/jobs/example-job/taskGroups/group0/tasks?filter=FILTER_EXPRESSION

FILTER_EXPRESSION 替换为使用网址编码过滤表达式

例如,您可以指定以下过滤表达式,以仅查看作业的任务组中正在运行或已成功运行的任务:

STATE=RUNNING%20OR%20STATE=SUCCEEDED

请注意,网址编码的过滤条件表达式表示以下已解码的过滤条件表达式:

STATE=RUNNING OR STATE=SUCCEEDED

Go

Go

如需了解详情,请参阅 Batch Go API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

	batch "cloud.google.com/go/batch/apiv1"
	"cloud.google.com/go/batch/apiv1/batchpb"
	"google.golang.org/api/iterator"
)

// Lists all tasks in the given project and region
func listTasks(w io.Writer, projectID, region, jobName, taskGroup string) error {
	// projectID := "your_project_id"
	// region := "us-central1"
	// jobName := "some-job"
	// taskGroup := "group0" // defaults to "group0" on job creation unless overridden

	ctx := context.Background()
	batchClient, err := batch.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer batchClient.Close()

	req := &batchpb.ListTasksRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s/jobs/%s/taskGroups/%s", projectID, region, jobName, taskGroup),
	}

	var tasks []*batchpb.Task
	it := batchClient.ListTasks(ctx, req)

	for {
		task, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("unable to list tasks: %w", err)
		}
		tasks = append(tasks, task)
	}

	fmt.Fprintf(w, "Tasks: %v\n", tasks)

	return nil
}

Java

Java

如需了解详情,请参阅 Batch Java API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.Task;
import java.io.IOException;

public class ListTasks {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // Name of the region hosts the job.
    String region = "europe-central2";
    // Name of the job which tasks you want to list.
    String jobName = "JOB_NAME";
    // Name of the group of tasks. Usually it's `group0`.
    String groupName = "group0";

    listTasks(projectId, region, jobName, groupName);
  }

  // Get a list of all jobs defined in given region.
  public static void listTasks(String projectId, String region, String jobName, String groupName)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `batchServiceClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (BatchServiceClient batchServiceClient = BatchServiceClient.create()) {

      String parent = String.format("projects/%s/locations/%s/jobs/%s/taskGroups/%s", projectId,
          region, jobName, groupName);
      for (Task task : batchServiceClient.listTasks(parent).iterateAll()) {
        System.out.println(task.getName());
      }
    }
  }
}

Node.js

Node.js

如需了解详情,请参阅 Batch Node.js API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
/**
 * The region that hosts the job.
 */
// const region = 'us-central-1';
/**
 * The name of the job which tasks you want to list.
 */
// const jobName = 'YOUR_JOB_NAME';
/**
 * The name of the group of tasks. Usually it's `group0`.
 */
// const groupName = 'group0';

// Imports the Batch library
const batchLib = require('@google-cloud/batch');

// Instantiates a client
const batchClient = new batchLib.v1.BatchServiceClient();

async function callListTasks() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${region}/jobs/${jobName}/taskGroups/${groupName}`,
  };

  // Run request
  const iterable = await batchClient.listTasksAsync(request);
  for await (const response of iterable) {
    console.log(response);
  }
}

callListTasks();

Python

Python

如需了解详情,请参阅 Batch Python API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

from __future__ import annotations

from collections.abc import Iterable

from google.cloud import batch_v1

def list_tasks(
    project_id: str, region: str, job_name: str, group_name: str
) -> Iterable[batch_v1.Task]:
    """
    Get a list of all jobs defined in given region.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        region: name of the region hosting the jobs.
        job_name: name of the job which tasks you want to list.
        group_name: name of the group of tasks. Usually it's `group0`.

    Returns:
        An iterable collection of Task objects.
    """
    client = batch_v1.BatchServiceClient()

    return client.list_tasks(
        parent=f"projects/{project_id}/locations/{region}/jobs/{job_name}/taskGroups/{group_name}"
    )

C++

C++

如需了解详情,请参阅 Batch C++ API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

#include "google/cloud/batch/v1/batch_client.h"

  [](std::string const& project_id, std::string const& location_id,
     std::string const& job_id, std::string const& group_id) {
    auto const parent = "projects/" + project_id + "/locations/" + location_id +
                        "/jobs/" + job_id + "/taskGroups/" + group_id;
    // Initialize a client and issue the request.
    auto client = google::cloud::batch_v1::BatchServiceClient(
        google::cloud::batch_v1::MakeBatchServiceConnection());
    int i = 0;
    for (auto task : client.ListTasks(parent)) {
      if (!task) throw std::move(task).status();
      std::cout << "Task[" << i++ << "]  " << task->DebugString() << "\n";
    }
  }

查看任务详情

您可以使用 Google Cloud 控制台、gcloud CLI、Batch API、Go、Java、Node.js、Python 或 C++ 查看任务的详细信息。

控制台

如需使用 Google Cloud 控制台查看任务详情,请查看作业详情,以打开作业详情页面。然后,查看任务详情部分。

gcloud

如需使用 gcloud CLI 查看任务的详细信息,请使用带有以下标志的 gcloud batch tasks describe 命令

gcloud batch tasks describe TASK_INDEX \
  --location=LOCATION \
  --job=JOB_NAME \
  --task_group=TASK_GROUP_NAME

替换以下内容:

  • TASK_INDEX:要查看其详情的任务的索引。在任务组中,第一个任务的任务索引从 0 开始,每增加一个任务,索引就会增加 1。例如,如果某个任务组包含四个任务,则其索引为 0123

  • TASK_GROUP_NAME:要查看其详细信息的任务所属的任务组的名称。该值必须设置为 group0

  • JOB_NAME:现有作业的名称。

  • LOCATION:作业所在的位置

API

如需使用 Batch API 查看任务的详细信息,请向 tasks.get 方法发出 GET 请求:

GET https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/jobs/JOB_NAME/taskGroups/TASK_GROUP_NAME/tasks/TASK_INDEX

替换以下内容:

  • PROJECT_ID:当前项目的项目 ID

  • LOCATION:作业所在的位置

  • JOB_NAME:现有作业的名称。

  • TASK_GROUP_NAME:要查看其详细信息的任务所属的任务组的名称。该值必须设置为 group0

  • TASK_INDEX:要查看其详细信息的任务的索引。在任务组中,第一个任务的任务索引从 0 开始,每增加一个任务,任务索引就会增加 1。例如,一个包含四个任务的任务组索引为 012、a 和 3

Go

Go

如需了解详情,请参阅 Batch Go API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

	batch "cloud.google.com/go/batch/apiv1"
	"cloud.google.com/go/batch/apiv1/batchpb"
)

// Retrieves the information about the specified job, most importantly its status
func getTask(w io.Writer, projectID, region, jobName, taskGroup string, taskNumber int32) error {
	// projectID := "your_project_id"
	// region := "us-central1"
	// jobName := "some-job"
	// taskGroup := "group0" // defaults to "group0" on job creation unless overridden
	// taskNumber := 0

	ctx := context.Background()
	batchClient, err := batch.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer batchClient.Close()

	req := &batchpb.GetTaskRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/jobs/%s/taskGroups/%s/tasks/%d",
			projectID, region, jobName, taskGroup, taskNumber),
	}

	response, err := batchClient.GetTask(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to get task: %w", err)
	}

	fmt.Fprintf(w, "Task info: %v\n", response)

	return nil
}

Java

Java

如需了解详情,请参阅 Batch Java API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.Task;
import com.google.cloud.batch.v1.TaskName;
import java.io.IOException;

public class GetTask {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // Name of the region hosts the job.
    String region = "europe-central2";
    // The name of the job you want to retrieve information about.
    String jobName = "JOB_NAME";
    // The name of the group that owns the task you want to check. Usually it's `group0`.
    String groupName = "group0";
    // Number of the task you want to look up.
    int taskNumber = 0;

    getTask(projectId, region, jobName, groupName, taskNumber);
  }

  // Retrieve information about a Task.
  public static void getTask(String projectId, String region, String jobName, String groupName,
      int taskNumber) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `batchServiceClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (BatchServiceClient batchServiceClient = BatchServiceClient.create()) {

      Task task = batchServiceClient.getTask(TaskName.newBuilder()
          .setProject(projectId)
          .setLocation(region)
          .setJob(jobName)
          .setTaskGroup(groupName)
          .setTask(String.valueOf(taskNumber))
          .build());
      System.out.printf("Retrieved task information: %s", task.getName());
    }
  }
}

Node.js

Node.js

如需了解详情,请参阅 Batch Node.js API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
/**
 * The region that hosts the job.
 */
// const region = 'us-central-1';
/**
 * The name of the job you want to retrieve information about.
 */
// const jobName = 'YOUR_JOB_NAME';
/**
 * The name of the group that owns the task you want to check.
 * Usually it's `group0`.
 */
// const groupName = 'group0';
/**
 * The number of the task you want to look up.
 */
// const taskNumber = 0;

// Imports the Batch library
const batchLib = require('@google-cloud/batch');

// Instantiates a client
const batchClient = new batchLib.v1.BatchServiceClient();

async function callGetJob() {
  // Construct request
  const request = {
    name:
      `projects/${projectId}/locations/${region}/jobs/${jobName}` +
      `/taskGroups/${groupName}/tasks/${taskNumber}`,
  };

  // Run request
  const response = await batchClient.getTask(request);
  console.log(response);
}

callGetJob();

Python

Python

如需了解详情,请参阅 Batch Python API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


from google.cloud import batch_v1

def get_task(
    project_id: str, region: str, job_name: str, group_name: str, task_number: int
) -> batch_v1.Task:
    """
    Retrieve information about a Task.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        region: name of the region hosts the job.
        job_name: the name of the job you want to retrieve information about.
        group_name: the name of the group that owns the task you want to check. Usually it's `group0`.
        task_number: number of the task you want to look up.

    Returns:
        A Task object representing the specified task.
    """
    client = batch_v1.BatchServiceClient()

    return client.get_task(
        name=f"projects/{project_id}/locations/{region}/jobs/{job_name}"
        f"/taskGroups/{group_name}/tasks/{task_number}"
    )

C++

C++

如需了解详情,请参阅 Batch C++ API 参考文档

要向 Batch 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

#include "google/cloud/batch/v1/batch_client.h"

  [](std::string const& project_id, std::string const& location_id,
     std::string const& job_id, std::string const& group_id,
     std::string const& task_number) {
    auto const name = "projects/" + project_id + "/locations/" + location_id +
                      "/jobs/" + job_id + "/taskGroups/" + group_id +
                      "/tasks/" + task_number;
    // Initialize a client and issue the request.
    auto client = google::cloud::batch_v1::BatchServiceClient(
        google::cloud::batch_v1::MakeBatchServiceConnection());
    auto response = client.GetTask(name);
    if (!response) throw std::move(response).status();
    std::cout << "GetTask() succeeded with " << response->DebugString() << "\n";
  }

后续步骤