Enumerar tareas

Un trabajo por lotes consta de una o varias tareas. Esta muestra recupera el nombre y el estado actual de todas las tareas en un trabajo determinado.

Explora más

Para obtener documentación en la que se incluye esta muestra de código, consulta lo siguiente:

Muestra de código

C++

Si deseas obtener más información, consulta la documentación de referencia de la API de Batch C++.

Para autenticarte en Batch, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Go

Si deseas obtener más información, consulta la documentación de referencia de la API de Batch Go.

Para autenticarte en Batch, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Si deseas obtener más información, consulta la documentación de referencia de la API de Batch Java.

Para autenticarte en Batch, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Si deseas obtener más información, consulta la documentación de referencia de la API de Batch Node.js.

Para autenticarte en Batch, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Si deseas obtener más información, consulta la documentación de referencia de la API de Batch Python.

Para autenticarte en Batch, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

¿Qué sigue?

Para buscar y filtrar muestras de código para otros productos de Google Cloud, consulta el navegador de muestra de Google Cloud.