Descrivere un'attività

Un job batch è costituito da una o più attività. Questo esempio recupera il nome e informazioni dettagliate sullo stato per una determinata attività.

Per saperne di più

Per la documentazione dettagliata che include questo esempio di codice, vedi quanto segue:

Esempio di codice

C++

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Batch C++.

Per eseguire l'autenticazione in Batch, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

#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";
  }

Go

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Batch Go.

Per eseguire l'autenticazione in Batch, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Batch Java.

Per eseguire l'autenticazione in Batch, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Batch Node.js.

Per eseguire l'autenticazione in Batch, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

/**
 * 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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Batch Python.

Per eseguire l'autenticazione in Batch, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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}"
    )

Passaggi successivi

Per cercare e filtrare esempi di codice per altri prodotti Google Cloud, consulta il browser di esempio Google Cloud.