建立及執行基本工作

本文說明如何建立 Batch 工作的基本概念:如何建立及執行以指令碼或容器映像檔為基礎的工作,以及如何使用預先定義和自訂變數。如要進一步瞭解如何建立及執行工作,請參閱工作建立和執行作業總覽

事前準備

  1. 如果您從未使用過 Batch,請參閱「開始使用 Batch」,並完成專案和使用者的必要條件,啟用 Batch。
  2. 如要取得建立作業所需的權限,請要求管理員授予下列 IAM 角色:

    如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

    您或許還可透過自訂角色或其他預先定義的角色取得必要權限。

  3. 每次建立工作時,請確保工作具有有效的網路設定。
    • 如果您的工作負載或專案沒有任何特定網路需求,且您未修改專案的預設網路,則無需採取任何行動。
    • 否則,您必須在建立工作時設定網路。瞭解如何為工作設定網路,再建立基本工作,以便修改下列範例,符合您的網路需求。
    如要進一步瞭解工作的網路設定,請參閱 Batch 網路總覽
  4. 每次建立工作時,請確保工作具有有效的 VM 作業系統 (OS) 環境。
    • 如果您的工作負載或專案沒有任何特定的 VM OS 映像檔或開機磁碟需求,則無需採取任何行動。
    • 否則,您必須準備有效的 VM OS 環境選項。建立基本工作前,請允許 VM OS 環境的預設設定,或瞭解如何自訂 VM OS 環境,以便修改下列範例來符合您的需求。
    如要進一步瞭解作業的 VM OS 環境,請參閱 VM OS 環境總覽

建立基本工作

如要瞭解可為工作指定的所有欄位,請參閱 projects.locations.jobs REST 資源的參考說明文件。總而言之,工作包含一或多個任務的陣列,這些任務都會執行一或多個可執行項目,也就是工作的可執行指令碼和/或容器。為說明基本概念,本節將說明如何建立範例工作,其中只包含一個可執行項目,可以是指令碼或容器映像檔:

  • 如要使用 Batch 撰寫執行容器映像檔的工作,請參閱建立容器工作
  • 否則,如果您不確定是否要使用容器映像檔,或不熟悉容器,建議建立指令碼工作

這兩種類型的工作範例都包含一個工作群組,其中含有 4 個工作的陣列。每項工作都會將訊息和索引列印至標準輸出和 Cloud Logging。這項工作的定義指定了 2 個並行,表示工作應在 2 個 VM 上執行,以便同時執行 2 項工作。

建立基本容器作業

您可以選取或建立容器映像檔,為作業提供程式碼和依附元件,以便從任何運算環境執行作業。詳情請參閱「使用容器映像檔」和「在 VM 執行個體上執行容器」。

您可以使用 Google Cloud 控制台、gcloud CLI、Batch API、Go、Java、Node.js、Python 或 C++,建立基本容器作業。

控制台

如要使用 Google Cloud 控制台建立基本容器作業,請按照下列步驟操作:

  1. 前往 Google Cloud 控制台的「Job list」(工作清單) 頁面。

    前往工作清單

  2. 按一下「 Create」(建立)。「Create batch job」(建立批次工作) 頁面隨即開啟。左側窗格會選取「工作詳細資料」頁面。

  3. 設定「工作詳細資料」頁面:

    1. 選用:在「Job name」(工作名稱) 欄位中,自訂工作名稱。

      例如輸入 example-basic-job

    2. 設定「工作詳細資料」部分:

      1. 在「New runnable」(新增可執行項目) 視窗中,為這項工作新增至少一個要執行的指令碼或容器。

        舉例來說,如要新增一個容器,請按照下列步驟操作:

        1. 選取「容器映像檔網址」 (預設)。

        2. 在「Container image URL」(容器映像檔網址) 欄位中,輸入要為這項工作中的各項任務執行的容器映像檔網址。

          舉例來說,如要使用 busybox Docker 容器映像檔,請輸入下列網址:

          gcr.io/google-containers/busybox
          
        3. 選用:如要覆寫容器映像檔的 ENTRYPOINT 指令,請在「進入點」欄位中輸入指令。

          例如輸入以下內容:

          /bin/sh
          
        4. 選用:如要覆寫容器映像檔的 CMD 指令,請執行下列步驟:

          1. 選取「覆寫容器映像檔的 CMD 指令」核取方塊。系統隨即會顯示欄位。

          2. 在欄位中輸入一或多個指令,並以換行符號分隔。

            例如,輸入下列指令:

            -c
            echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks.
            
          3. 按一下 [完成]

      2. 在「工作數」欄位中,輸入這項工作的工作數。這個值必須是介於 1每個工作群組的工作數上限之間的整數。

        例如輸入 4

      3. 在「Parallelism」(平行處理) 欄位中,輸入要同時執行的任務數量。這個數字不得大於任務總數,且必須是介於 1每個工作並行任務數量上限之間的整數。

        例如輸入 2

  4. 設定「資源規格」頁面:

    1. 在左側窗格中,按一下「資源規格」。 「資源規格」頁面隨即開啟。

    2. 在「VM 佈建模式」部分,為這項作業的 VM 選取下列其中一個佈建模式

      • 如果工作可以承受先占,且您希望使用折扣 VM,請選取「Spot」

      • 否則請選取「標準」

      例如選取「標準」(預設)

    3. 選取這項工作的地點

      1. 在「Region」(區域) 欄位中選取區域。

        例如,選取 us-central1 (Iowa) (預設)。

      2. 在「區域」欄位中,執行下列任一操作:

        • 如要限制這項工作只能在特定區域中執行,請選取區域。

        • 否則請選取「不限」

        例如選取「any」(任何) (預設)。

    4. 選取下列其中一個機器系列

      • 如為一般工作負載,請按一下「一般用途」

      • 如要處理需要大量運算資源的工作負載,請按一下「運算最佳化」

      • 如要處理須耗用大量記憶體的工作負載,請按一下「記憶體最佳化」

      • 如要查看加速器最佳化工作負載,請按一下「GPU」。詳情請參閱建立及執行使用 GPU 的工作

      例如按一下「一般用途」 (預設)。

    5. 在「系列」欄位中,選取這項工作 VM 的機器系列

      舉例來說,如果您為機器系列選取「一般用途」,請選取「E2」 (預設)。

    6. 在「Machine type」(機器類型) 欄位中,選取這項作業 VM 的機器類型。

      舉例來說,如果您為機器系列選取「E2」,請選取「e2-medium (2 個 vCPU,4 GB 記憶體)」 (預設)。

    7. 設定各項工作所需的 VM 資源量:

      1. 在「Cores」(核心) 欄位中,輸入每個工作使用的 vCPUs 數量。

        例如,輸入 1 (預設值)。

      2. 在「記憶體」欄位中,輸入每個工作使用的 RAM 容量 (以 GB 為單位)。

        例如,輸入 0.5 (預設值)。

  5. 選用:如要檢查工作設定,請在左側窗格中按一下「預覽」

  6. 點選「建立」

「Job details」(工作詳細資料) 頁面會顯示您建立的工作。

gcloud

如要使用 gcloud CLI 建立基本容器工作,請執行下列操作:

  1. 建立 JSON 檔案,指定作業的設定詳細資料。舉例來說,如要建立基本容器作業,請建立含有下列內容的 JSON 檔案。如要進一步瞭解可為工作指定的所有欄位,請參閱 projects.locations.jobs REST 資源的參考說明文件。

    {
        "taskGroups": [
            {
                "taskSpec": {
                    "runnables": [
                        {
                            "container": {
                                CONTAINER
                            }
                        }
                    ],
                    "computeResource": {
                        "cpuMilli": CORES,
                        "memoryMib": MEMORY
                    },
                    "maxRetryCount": MAX_RETRY_COUNT,
                    "maxRunDuration": "MAX_RUN_DURATION"
                },
                "taskCount": TASK_COUNT,
                "parallelism": PARALLELISM
            }
        ]
    }
    

    更改下列內容:

    • CONTAINER:每個工作執行的容器。 容器至少須在 imageUri 子欄位中指定圖片,但可能也需要其他子欄位。詳情請參閱本節中的container 子欄位和範例容器工作。
    • CORES:選用。要為每個工作分配的核心數量 (以 milliCPU 為單位),具體來說是 vCPUs,通常代表半個實體核心。如未指定 cpuMilli 欄位,系統會將值設為 2000 (2 個 vCPU)。
    • MEMORY:選用。以 MB 為單位,為每個工作分配的記憶體量。如未指定 memoryMib 欄位,系統會將值設為 2000 (2 GB)。
    • MAX_RETRY_COUNT:選用。工作重試次數上限。這個值必須是介於 010 之間的整數。如未指定 maxRetryCount 欄位,系統會將值設為 0,表示不重試工作。如要進一步瞭解 maxRetryCount 欄位,請參閱「自動重試工作」。
    • MAX_RUN_DURATION:選用。工作重試或失敗前可執行的時間上限,格式為以秒為單位的數值,後接 s,例如 3600s 代表 1 小時。如果未指定 maxRunDuration 欄位,系統會將值設為工作最長執行時間。如要進一步瞭解 maxRunDuration 欄位,請參閱「使用逾時限制工作和可執行項目的執行時間」。
    • TASK_COUNT:選用。工作的工作數量。這個值必須是介於 1每個工作群組的工作數量上限之間的整數。如未指定 taskCount 欄位,系統會將值設為 1
    • PARALLELISM:選用。工作並行執行的任務數量。這個數字不得大於任務數量,且必須是介於 1每個工作並行任務數量上限之間的整數。如未指定 parallelism 欄位,系統會將值設為 1
  2. 使用 gcloud batch jobs submit 指令建立工作。

    gcloud batch jobs submit JOB_NAME \
      --location LOCATION \
      --config JSON_CONFIGURATION_FILE
    

    更改下列內容:

    • JOB_NAME:作業名稱。
    • LOCATION:工作地點
    • JSON_CONFIGURATION_FILE:JSON 檔案的路徑,內含作業的設定詳細資料。

舉例來說,如要建立使用 busybox Docker 容器映像檔執行工作的作業:

  1. 在目前目錄中建立名為 hello-world-container.json 的 JSON 檔案,並加入下列內容:

    {
        "taskGroups": [
            {
                "taskSpec": {
                    "runnables": [
                        {
                            "container": {
                                "imageUri": "gcr.io/google-containers/busybox",
                                "entrypoint": "/bin/sh",
                                "commands": [
                                    "-c",
                                    "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
                                ]
                            }
                        }
                    ],
                    "computeResource": {
                        "cpuMilli": 2000,
                        "memoryMib": 16
                    },
                    "maxRetryCount": 2,
                    "maxRunDuration": "3600s"
                },
                "taskCount": 4,
                "parallelism": 2
            }
        ],
        "allocationPolicy": {
            "instances": [
                {
                    "policy": { "machineType": "e2-standard-4" }
                }
            ]
        },
        "labels": {
            "department": "finance",
            "env": "testing"
        },
        "logsPolicy": {
            "destination": "CLOUD_LOGGING"
        }
    }
    
  2. 執行下列指令:

    gcloud batch jobs submit example-container-job \
      --location us-central1 \
      --config hello-world-container.json
    

API

如要使用 Batch API 建立基本容器工作,請使用 jobs.create 方法。如要進一步瞭解可為工作指定的所有欄位,請參閱 projects.locations.jobs REST 資源的參考說明文件。

POST https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/jobs?job_id=JOB_NAME

{
    "taskGroups": [
        {
            "taskSpec": {
                "runnables": [
                    {
                        "container": {
                            CONTAINER
                        }
                    }
                ],
                "computeResource": {
                    "cpuMilli": CORES,
                    "memoryMib": MEMORY
                },
                "maxRetryCount": MAX_RETRY_COUNT,
                "maxRunDuration": "MAX_RUN_DURATION"
            },
            "taskCount": TASK_COUNT,
            "parallelism": PARALLELISM
        }
    ]
}

更改下列內容:

  • PROJECT_ID:專案的專案 ID
  • LOCATION:工作地點
  • JOB_NAME:作業名稱。
  • CONTAINER:每個工作執行的容器。 容器至少須在 imageUri 子欄位中指定圖片,但可能也需要其他子欄位。詳情請參閱本節中的container 子欄位和範例容器工作。
  • CORES:選用。要為每個工作分配的核心數量,以 milliCPU 為單位。具體來說,就是 vCPUs 數量,通常代表半個實體核心。如未指定 cpuMilli 欄位,系統會將值設為 2000 (2 個 vCPU)。
  • MEMORY:選用。以 MB 為單位,為每個工作分配的記憶體量。如未指定 memoryMib 欄位,系統會將值設為 2000 (2 GB)。
  • MAX_RETRY_COUNT:選用。工作重試次數上限。這個值必須是介於 010 之間的整數。如未指定 maxRetryCount 欄位,系統會將值設為 0,表示不重試工作。如要進一步瞭解 maxRetryCount 欄位,請參閱「自動重試工作」。
  • MAX_RUN_DURATION:選用。工作重試或失敗前可執行的時間上限,格式為以秒為單位的數值,後接 s,例如 3600s 代表 1 小時。如果未指定 maxRunDuration 欄位,系統會將值設為工作的最長執行時間。如要進一步瞭解 maxRunDuration 欄位,請參閱「使用逾時限制工作和可執行項目的執行時間」。
  • TASK_COUNT:選用。這項作業的任務數量,必須是介於 1每個任務群組的任務數量上限之間的整數。如未指定 taskCount 欄位,系統會將值設為 1
  • PARALLELISM:選用。工作並行執行的任務數量。這個數字不得大於任務數量,且必須是介於 1每個工作並行任務數量上限之間的整數。如未指定 parallelism 欄位,系統會將值設為 1

舉例來說,如要建立使用 busybox Docker 容器映像檔執行工作的作業,請使用下列要求:

POST https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/jobs?job_id=example-container-job

{
    "taskGroups": [
        {
            "taskSpec": {
                "runnables": [
                    {
                        "container": {
                            "imageUri": "gcr.io/google-containers/busybox",
                            "entrypoint": "/bin/sh",
                            "commands": [
                                "-c",
                                "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
                            ]
                        }
                    }
                ],
                "computeResource": {
                    "cpuMilli": 2000,
                    "memoryMib": 16
                },
                "maxRetryCount": 2,
                "maxRunDuration": "3600s"
            },
            "taskCount": 4,
            "parallelism": 2
        }
    ],
    "allocationPolicy": {
        "instances": [
            {
                "policy": { "machineType": "e2-standard-4" }
            }
        ]
    },
    "labels": {
        "department": "finance",
        "env": "testing"
    },
    "logsPolicy": {
        "destination": "CLOUD_LOGGING"
    }
}

其中 PROJECT_ID 是專案的專案 ID

Go

Go

詳情請參閱 Batch Go API 參考說明文件

如要向 Batch 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"fmt"
	"io"

	batch "cloud.google.com/go/batch/apiv1"
	"cloud.google.com/go/batch/apiv1/batchpb"
	durationpb "google.golang.org/protobuf/types/known/durationpb"
)

// Creates and runs a job that runs the specified container
func createContainerJob(w io.Writer, projectID, region, jobName string) error {
	// projectID := "your_project_id"
	// region := "us-central1"
	// jobName := "some-job"

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

	container := &batchpb.Runnable_Container{
		ImageUri:   "gcr.io/google-containers/busybox",
		Commands:   []string{"-c", "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."},
		Entrypoint: "/bin/sh",
	}

	// We can specify what resources are requested by each task.
	resources := &batchpb.ComputeResource{
		// CpuMilli is milliseconds per cpu-second. This means the task requires 2 whole CPUs.
		CpuMilli:  2000,
		MemoryMib: 16,
	}

	taskSpec := &batchpb.TaskSpec{
		Runnables: []*batchpb.Runnable{{
			Executable: &batchpb.Runnable_Container_{Container: container},
		}},
		ComputeResource: resources,
		MaxRunDuration: &durationpb.Duration{
			Seconds: 3600,
		},
		MaxRetryCount: 2,
	}

	// Tasks are grouped inside a job using TaskGroups.
	taskGroups := []*batchpb.TaskGroup{
		{
			TaskCount: 4,
			TaskSpec:  taskSpec,
		},
	}

	// Policies are used to define on what kind of virtual machines the tasks will run on.
	// In this case, we tell the system to use "e2-standard-4" machine type.
	// Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
	allocationPolicy := &batchpb.AllocationPolicy{
		Instances: []*batchpb.AllocationPolicy_InstancePolicyOrTemplate{{
			PolicyTemplate: &batchpb.AllocationPolicy_InstancePolicyOrTemplate_Policy{
				Policy: &batchpb.AllocationPolicy_InstancePolicy{
					MachineType: "e2-standard-4",
				},
			},
		}},
	}

	// We use Cloud Logging as it's an out of the box available option
	logsPolicy := &batchpb.LogsPolicy{
		Destination: batchpb.LogsPolicy_CLOUD_LOGGING,
	}

	jobLabels := map[string]string{"env": "testing", "type": "container"}

	// The job's parent is the region in which the job will run
	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, region)

	job := batchpb.Job{
		TaskGroups:       taskGroups,
		AllocationPolicy: allocationPolicy,
		Labels:           jobLabels,
		LogsPolicy:       logsPolicy,
	}

	req := &batchpb.CreateJobRequest{
		Parent: parent,
		JobId:  jobName,
		Job:    &job,
	}

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

	fmt.Fprintf(w, "Job created: %v\n", created_job)

	return nil
}

Java

Java

詳情請參閱 Batch Java API 參考說明文件

如要向 Batch 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import com.google.cloud.batch.v1.AllocationPolicy;
import com.google.cloud.batch.v1.AllocationPolicy.InstancePolicy;
import com.google.cloud.batch.v1.AllocationPolicy.InstancePolicyOrTemplate;
import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.ComputeResource;
import com.google.cloud.batch.v1.CreateJobRequest;
import com.google.cloud.batch.v1.Job;
import com.google.cloud.batch.v1.LogsPolicy;
import com.google.cloud.batch.v1.LogsPolicy.Destination;
import com.google.cloud.batch.v1.Runnable;
import com.google.cloud.batch.v1.Runnable.Container;
import com.google.cloud.batch.v1.TaskGroup;
import com.google.cloud.batch.v1.TaskSpec;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateWithContainerNoMounting {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // 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 you want to use to run the job. Regions that are
    // available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
    String region = "europe-central2";

    // The name of the job that will be created.
    // It needs to be unique for each project and region pair.
    String jobName = "JOB_NAME";

    createContainerJob(projectId, region, jobName);
  }

  // This method shows how to create a sample Batch Job that will run a simple command inside a
  // container on Cloud Compute instances.
  public static void createContainerJob(String projectId, String region, String jobName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // 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()) {

      // Define what will be done as part of the job.
      Runnable runnable =
          Runnable.newBuilder()
              .setContainer(
                  Container.newBuilder()
                      .setImageUri("gcr.io/google-containers/busybox")
                      .setEntrypoint("/bin/sh")
                      .addCommands("-c")
                      .addCommands(
                          "echo Hello world! This is task ${BATCH_TASK_INDEX}. "
                              + "This job has a total of ${BATCH_TASK_COUNT} tasks.")
                      .build())
              .build();

      // We can specify what resources are requested by each task.
      ComputeResource computeResource =
          ComputeResource.newBuilder()
              // In milliseconds per cpu-second. This means the task requires 2 whole CPUs.
              .setCpuMilli(2000)
              // In MiB.
              .setMemoryMib(16)
              .build();

      TaskSpec task =
          TaskSpec.newBuilder()
              // Jobs can be divided into tasks. In this case, we have only one task.
              .addRunnables(runnable)
              .setComputeResource(computeResource)
              .setMaxRetryCount(2)
              .setMaxRunDuration(Duration.newBuilder().setSeconds(3600).build())
              .build();

      // Tasks are grouped inside a job using TaskGroups.
      // Currently, it's possible to have only one task group.
      TaskGroup taskGroup = TaskGroup.newBuilder().setTaskCount(4).setTaskSpec(task).build();

      // Policies are used to define on what kind of virtual machines the tasks will run on.
      // In this case, we tell the system to use "e2-standard-4" machine type.
      // Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
      InstancePolicy instancePolicy =
          InstancePolicy.newBuilder().setMachineType("e2-standard-4").build();

      AllocationPolicy allocationPolicy =
          AllocationPolicy.newBuilder()
              .addInstances(InstancePolicyOrTemplate.newBuilder().setPolicy(instancePolicy).build())
              .build();

      Job job =
          Job.newBuilder()
              .addTaskGroups(taskGroup)
              .setAllocationPolicy(allocationPolicy)
              .putLabels("env", "testing")
              .putLabels("type", "container")
              // We use Cloud Logging as it's an out of the box available option.
              .setLogsPolicy(
                  LogsPolicy.newBuilder().setDestination(Destination.CLOUD_LOGGING).build())
              .build();

      CreateJobRequest createJobRequest =
          CreateJobRequest.newBuilder()
              // The job's parent is the region in which the job will run.
              .setParent(String.format("projects/%s/locations/%s", projectId, region))
              .setJob(job)
              .setJobId(jobName)
              .build();

      Job result =
          batchServiceClient
              .createJobCallable()
              .futureCall(createJobRequest)
              .get(5, TimeUnit.MINUTES);

      System.out.printf("Successfully created the job: %s", result.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 you want to the job to run in. The regions that support Batch are listed here:
 * https://cloud.google.com/batch/docs/get-started#locations
 */
// const region = 'us-central-1';
/**
 * The name of the job that will be created.
 * It needs to be unique for each project and region pair.
 */
// const jobName = 'YOUR_JOB_NAME';

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

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

// Define what will be done as part of the job.
const task = new batch.TaskSpec();
const runnable = new batch.Runnable();
runnable.container = new batch.Runnable.Container();
runnable.container.imageUri = 'gcr.io/google-containers/busybox';
runnable.container.entrypoint = '/bin/sh';
runnable.container.commands = [
  '-c',
  'echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks.',
];
task.runnables = [runnable];

// We can specify what resources are requested by each task.
const resources = new batch.ComputeResource();
resources.cpuMilli = 2000; // in milliseconds per cpu-second. This means the task requires 2 whole CPUs.
resources.memoryMib = 16;
task.computeResource = resources;

task.maxRetryCount = 2;
task.maxRunDuration = {seconds: 3600};

// Tasks are grouped inside a job using TaskGroups.
const group = new batch.TaskGroup();
group.taskCount = 4;
group.taskSpec = task;

// Policies are used to define on what kind of virtual machines the tasks will run on.
// In this case, we tell the system to use "e2-standard-4" machine type.
// Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
const allocationPolicy = new batch.AllocationPolicy();
const policy = new batch.AllocationPolicy.InstancePolicy();
policy.machineType = 'e2-standard-4';
const instances = new batch.AllocationPolicy.InstancePolicyOrTemplate();
instances.policy = policy;
allocationPolicy.instances = [instances];

const job = new batch.Job();
job.name = jobName;
job.taskGroups = [group];
job.allocationPolicy = allocationPolicy;
job.labels = {env: 'testing', type: 'container'};
// We use Cloud Logging as it's an option available out of the box
job.logsPolicy = new batch.LogsPolicy();
job.logsPolicy.destination = batch.LogsPolicy.Destination.CLOUD_LOGGING;

// The job's parent is the project and region in which the job will run
const parent = `projects/${projectId}/locations/${region}`;

async function callCreateJob() {
  // Construct request
  const request = {
    parent,
    jobId: jobName,
    job,
  };

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

await callCreateJob();

Python

Python

詳情請參閱 Batch Python API 參考說明文件

如要向 Batch 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from google.cloud import batch_v1


def create_container_job(project_id: str, region: str, job_name: str) -> batch_v1.Job:
    """
    This method shows how to create a sample Batch Job that will run
    a simple command inside a container on Cloud Compute instances.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        region: name of the region you want to use to run the job. Regions that are
            available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
        job_name: the name of the job that will be created.
            It needs to be unique for each project and region pair.

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

    # Define what will be done as part of the job.
    runnable = batch_v1.Runnable()
    runnable.container = batch_v1.Runnable.Container()
    runnable.container.image_uri = "gcr.io/google-containers/busybox"
    runnable.container.entrypoint = "/bin/sh"
    runnable.container.commands = [
        "-c",
        "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks.",
    ]

    # Jobs can be divided into tasks. In this case, we have only one task.
    task = batch_v1.TaskSpec()
    task.runnables = [runnable]

    # We can specify what resources are requested by each task.
    resources = batch_v1.ComputeResource()
    resources.cpu_milli = 2000  # in milliseconds per cpu-second. This means the task requires 2 whole CPUs.
    resources.memory_mib = 16  # in MiB
    task.compute_resource = resources

    task.max_retry_count = 2
    task.max_run_duration = "3600s"

    # Tasks are grouped inside a job using TaskGroups.
    # Currently, it's possible to have only one task group.
    group = batch_v1.TaskGroup()
    group.task_count = 4
    group.task_spec = task

    # Policies are used to define on what kind of virtual machines the tasks will run on.
    # In this case, we tell the system to use "e2-standard-4" machine type.
    # Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
    policy = batch_v1.AllocationPolicy.InstancePolicy()
    policy.machine_type = "e2-standard-4"
    instances = batch_v1.AllocationPolicy.InstancePolicyOrTemplate()
    instances.policy = policy
    allocation_policy = batch_v1.AllocationPolicy()
    allocation_policy.instances = [instances]

    job = batch_v1.Job()
    job.task_groups = [group]
    job.allocation_policy = allocation_policy
    job.labels = {"env": "testing", "type": "container"}
    # We use Cloud Logging as it's an out of the box available option
    job.logs_policy = batch_v1.LogsPolicy()
    job.logs_policy.destination = batch_v1.LogsPolicy.Destination.CLOUD_LOGGING

    create_request = batch_v1.CreateJobRequest()
    create_request.job = job
    create_request.job_id = job_name
    # The job's parent is the region in which the job will run
    create_request.parent = f"projects/{project_id}/locations/{region}"

    return client.create_job(create_request)

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) {
    // Initialize the request; start with the fields that depend on the sample
    // input.
    google::cloud::batch::v1::CreateJobRequest request;
    request.set_parent("projects/" + project_id + "/locations/" + location_id);
    request.set_job_id(job_id);
    // Most of the job description is fixed in this example; use a string to
    // initialize it.
    auto constexpr kText = R"pb(
      task_groups {
        task_count: 4
        task_spec {
          compute_resource { cpu_milli: 500 memory_mib: 16 }
          max_retry_count: 2
          max_run_duration { seconds: 3600 }
          runnables {
            container {
              image_uri: "gcr.io/google-containers/busybox"
              entrypoint: "/bin/sh"
              commands: "-c"
              commands: "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
            }
          }
        }
      }
      allocation_policy {
        instances {
          policy { machine_type: "e2-standard-4" provisioning_model: STANDARD }
        }
      }
      labels { key: "env" value: "testing" }
      labels { key: "type" value: "container" }
      logs_policy { destination: CLOUD_LOGGING }
    )pb";
    auto* job = request.mutable_job();
    if (!google::protobuf::TextFormat::ParseFromString(kText, job)) {
      throw std::runtime_error("Error parsing Job description");
    }
    // Create a client and issue the request.
    auto client = google::cloud::batch_v1::BatchServiceClient(
        google::cloud::batch_v1::MakeBatchServiceConnection());
    auto response = client.CreateJob(request);
    if (!response) throw std::move(response).status();
    std::cout << "Job : " << response->DebugString() << "\n";
  }

建立基本指令碼工作

您可以使用 Google Cloud 控制台、gcloud CLI、Batch API、Go、Java、Node.js、Python 或 C++,建立基本指令碼工作。

控制台

如要使用 Google Cloud 控制台建立基本指令碼作業,請按照下列步驟操作:

  1. 前往 Google Cloud 控制台的「Job list」(工作清單) 頁面。

    前往工作清單

  2. 按一下「 Create」(建立)。「Create batch job」(建立批次工作) 頁面隨即開啟。左側窗格會選取「工作詳細資料」頁面。

  3. 設定「工作詳細資料」頁面:

    1. 選用:在「Job name」(工作名稱) 欄位中,自訂工作名稱。

      例如輸入 example-basic-job

    2. 設定「工作詳細資料」部分:

      1. 在「New runnable」(新增可執行項目) 視窗中,為這項工作新增至少一個要執行的指令碼或容器。

        舉例來說,如要新增一個指令碼,請按照下列步驟操作:

        1. 選取「指令碼」。系統隨即會顯示欄位。

        2. 在欄位中輸入要為這項工作中的每項工作執行的指令碼。

          例如輸入下列指令碼:

          echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks.
          
        3. 按一下 [完成]

      2. 在「工作數」欄位中,輸入這項工作的工作數。這個值必須是介於 1每個工作群組的工作數上限之間的整數。

        例如輸入 4

      3. 在「Parallelism」(平行處理) 欄位中,輸入要同時執行的任務數量。這個數字不得大於任務總數,且必須是介於 1每個工作並行任務數量上限之間的整數。

        例如輸入 2

  4. 設定「資源規格」頁面:

    1. 在左側窗格中,按一下「資源規格」。 「資源規格」頁面隨即開啟。

    2. 在「VM 佈建模式」部分,為這項作業的 VM 選取下列其中一個佈建模式

      • 如果工作可以承受先占,且您希望使用折扣 VM,請選取「Spot」

      • 否則請選取「標準」

      例如選取「標準」(預設)

    3. 選取這項工作的地點

      1. 在「Region」(區域) 欄位中選取區域。

        例如,選取 us-central1 (Iowa) (預設)。

      2. 在「區域」欄位中,執行下列任一操作:

        • 如要限制這項工作只能在特定區域中執行,請選取區域。

        • 否則請選取「不限」

        例如選取「any」(任何) (預設)。

    4. 選取下列其中一個機器系列

      • 如為一般工作負載,請按一下「一般用途」

      • 如要處理需要大量運算資源的工作負載,請按一下「運算最佳化」

      • 如要處理須耗用大量記憶體的工作負載,請按一下「記憶體最佳化」

      • 如要查看加速器最佳化工作負載,請按一下「GPU」。詳情請參閱建立及執行使用 GPU 的工作

      例如按一下「一般用途」 (預設)。

    5. 在「系列」欄位中,選取這項工作 VM 的機器系列

      舉例來說,如果您為機器系列選取「一般用途」,請選取「E2」 (預設)。

    6. 在「Machine type」(機器類型) 欄位中,選取這項作業 VM 的機器類型。

      舉例來說,如果您為機器系列選取「E2」,請選取「e2-medium (2 個 vCPU,4 GB 記憶體)」 (預設)。

    7. 設定各項工作所需的 VM 資源量:

      1. 在「Cores」(核心) 欄位中,輸入每個工作使用的 vCPUs 數量。

        例如,輸入 1 (預設值)。

      2. 在「記憶體」欄位中,輸入每個工作使用的 RAM 容量 (以 GB 為單位)。

        例如,輸入 0.5 (預設值)。

  5. 選用:如要檢查工作設定,請在左側窗格中按一下「預覽」

  6. 點選「建立」

    「Job details」(工作詳細資料) 頁面會顯示您建立的工作。

gcloud

如要使用 gcloud CLI 建立基本指令碼工作,請執行下列操作:

  1. 建立 JSON 檔案,指定作業的設定詳細資料。舉例來說,如要建立基本指令碼作業,請建立內容如下的 JSON 檔案。如要進一步瞭解可為工作指定的所有欄位,請參閱 projects.locations.jobs REST 資源的參考說明文件。

    {
        "taskGroups": [
            {
                "taskSpec": {
                    "runnables": [
                        {
                            "script": {
                                SCRIPT
                            }
                        }
                    ],
                    "computeResource": {
                        "cpuMilli": CORES,
                        "memoryMib": MEMORY
                    },
                    "maxRetryCount": MAX_RETRY_COUNT,
                    "maxRunDuration": "MAX_RUN_DURATION"
                },
                "taskCount": TASK_COUNT,
                "parallelism": PARALLELISM
            }
        ]
    }
    

    更改下列內容:

    • SCRIPT:每個工作執行的指令碼。指令碼必須定義為使用 text 子欄位的文字,或使用 path 子欄位可存取檔案的路徑。詳情請參閱本節中的script 子欄位和範例指令碼工作。
    • CORES:選用。要為每個工作分配的核心數量 (以 milliCPU 為單位),具體來說是 vCPUs,通常代表半個實體核心。如未指定 cpuMilli 欄位,系統會將值設為 2000 (2 個 vCPU)。
    • MEMORY:選用。以 MB 為單位,為每個工作分配的記憶體量。如未指定 memoryMib 欄位,系統會將值設為 2000 (2 GB)。
    • MAX_RETRY_COUNT:選用。工作重試次數上限。這個值必須是介於 010 之間的整數。如未指定 maxRetryCount 欄位,系統會將值設為 0,表示不重試工作。如要進一步瞭解 maxRetryCount 欄位,請參閱「自動重試工作」。
    • MAX_RUN_DURATION:選用。工作重試或失敗前可執行的時間上限,格式為以秒為單位的數值,後接 s,例如 3600s 代表 1 小時。如果未指定 maxRunDuration 欄位,系統會將值設為工作最長執行時間。如要進一步瞭解 maxRunDuration 欄位,請參閱「使用逾時限制工作和可執行項目的執行時間」。
    • TASK_COUNT:選用。工作的工作數量。這個值必須是介於 1每個工作群組的工作數量上限之間的整數。如未指定 taskCount 欄位,系統會將值設為 1
    • PARALLELISM:選用。工作並行執行的任務數量。這個數字不得大於任務數量,且必須是介於 1每個工作並行任務數量上限之間的整數。如未指定 parallelism 欄位,系統會將值設為 1
  2. 使用 gcloud batch jobs submit 指令建立工作。

    gcloud batch jobs submit JOB_NAME \
      --location LOCATION \
      --config JSON_CONFIGURATION_FILE
    

    更改下列內容:

    • JOB_NAME:作業名稱。
    • LOCATION:工作地點
    • JSON_CONFIGURATION_FILE:JSON 檔案的路徑,內含作業的設定詳細資料。

舉例來說,如要建立工作,使用指令碼執行工作:

  1. 在目前目錄中建立名為 hello-world-script.json 的 JSON 檔案,並加入下列內容:

    {
        "taskGroups": [
            {
                "taskSpec": {
                    "runnables": [
                        {
                            "script": {
                                "text": "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
                            }
                        }
                    ],
                    "computeResource": {
                        "cpuMilli": 2000,
                        "memoryMib": 16
                    },
                    "maxRetryCount": 2,
                    "maxRunDuration": "3600s"
                },
                "taskCount": 4,
                "parallelism": 2
            }
        ],
        "allocationPolicy": {
            "instances": [
                {
                    "policy": { "machineType": "e2-standard-4" }
                }
            ]
        },
        "labels": {
            "department": "finance",
            "env": "testing"
        },
        "logsPolicy": {
            "destination": "CLOUD_LOGGING"
        }
    }
    
  2. 執行下列指令:

    gcloud batch jobs submit example-script-job \
      --location us-central1 \
      --config hello-world-script.json
    

API

如要使用 Batch API 建立基本指令碼工作,請使用 jobs.create 方法。如要進一步瞭解可為工作指定的所有欄位,請參閱 projects.locations.jobs REST 資源的參考說明文件。

POST https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/jobs?job_id=JOB_NAME

{
    "taskGroups": [
        {
            "taskSpec": {
                "runnables": [
                    {
                        "script": {
                            SCRIPT
                        }
                    }
                ],
                "computeResource": {
                    "cpuMilli": CORES,
                    "memoryMib": MEMORY
                },
                "maxRetryCount": MAX_RETRY_COUNT,
                "maxRunDuration": "MAX_RUN_DURATION"
            },
            "taskCount": TASK_COUNT,
            "parallelism": PARALLELISM
        }
    ]
}

更改下列內容:

  • PROJECT_ID:專案的專案 ID
  • LOCATION:工作地點
  • JOB_NAME:作業名稱。
  • SCRIPT:每個工作執行的指令碼。指令碼必須定義為使用 text 子欄位的文字,或使用 path 子欄位可存取檔案的路徑。詳情請參閱本節中的script 子欄位和範例指令碼工作。
  • CORES:選用。要為每個工作分配的核心數量,以 milliCPU 為單位。具體來說,就是 vCPUs 數量,通常代表半個實體核心。如未指定 cpuMilli 欄位,系統會將值設為 2000 (2 個 vCPU)。
  • MEMORY:選用。以 MB 為單位,為每個工作分配的記憶體量。如未指定 memoryMib 欄位,系統會將值設為 2000 (2 GB)。
  • MAX_RETRY_COUNT:選用。工作重試次數上限。這個值必須是介於 010 之間的整數。如未指定 maxRetryCount 欄位,系統會將值設為 0,表示不重試工作。如要進一步瞭解 maxRetryCount 欄位,請參閱「自動重試工作」。
  • MAX_RUN_DURATION:選用。工作重試或失敗前可執行的時間上限,格式為以秒為單位的數值,後接 s,例如 3600s 代表 1 小時。如果未指定 maxRunDuration 欄位,系統會將值設為工作的最長執行時間。如要進一步瞭解 maxRunDuration 欄位,請參閱「使用逾時限制工作和可執行項目的執行時間」。
  • TASK_COUNT:選用。這項工作的工作數量。這個值必須是介於 1每個工作群組的工作數量上限之間的整數。如未指定 taskCount 欄位,系統會將值設為 1
  • PARALLELISM:選用。工作並行執行的任務數量。這個數字不得大於任務數量,且必須是介於 1每個工作並行任務數量上限之間的整數。如未指定 parallelism 欄位,系統會將值設為 1

舉例來說,如要建立使用指令碼執行工作的工作,請使用下列要求:

POST https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/jobs?job_id=example-script-job

{
    "taskGroups": [
        {
            "taskSpec": {
                "runnables": [
                    {
                        "script": {
                            "text": "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
                        }
                    }
                ],
                "computeResource": {
                    "cpuMilli": 2000,
                    "memoryMib": 16
                },
                "maxRetryCount": 2,
                "maxRunDuration": "3600s"
            },
            "taskCount": 4,
            "parallelism": 2
        }
    ],
    "allocationPolicy": {
        "instances": [
            {
                "policy": { "machineType": "e2-standard-4" }
            }
        ]
    },
    "labels": {
        "department": "finance",
        "env": "testing"
    },
    "logsPolicy": {
        "destination": "CLOUD_LOGGING"
    }
}

其中 PROJECT_ID 是專案的專案 ID

Go

Go

詳情請參閱 Batch Go API 參考說明文件

如要向 Batch 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"fmt"
	"io"

	batch "cloud.google.com/go/batch/apiv1"
	"cloud.google.com/go/batch/apiv1/batchpb"
	durationpb "google.golang.org/protobuf/types/known/durationpb"
)

// Creates and runs a job that executes the specified script
func createScriptJob(w io.Writer, projectID, region, jobName string) error {
	// projectID := "your_project_id"
	// region := "us-central1"
	// jobName := "some-job"

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

	// Define what will be done as part of the job.
	command := &batchpb.Runnable_Script_Text{
		Text: "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks.",
	}
	// You can also run a script from a file. Just remember, that needs to be a script that's
	// already on the VM that will be running the job.
	// Using runnable.script.text and runnable.script.path is mutually exclusive.
	// command := &batchpb.Runnable_Script_Path{
	// 	Path: "/tmp/test.sh",
	// }

	// We can specify what resources are requested by each task.
	resources := &batchpb.ComputeResource{
		// CpuMilli is milliseconds per cpu-second. This means the task requires 2 whole CPUs.
		CpuMilli:  2000,
		MemoryMib: 16,
	}

	taskSpec := &batchpb.TaskSpec{
		Runnables: []*batchpb.Runnable{{
			Executable: &batchpb.Runnable_Script_{
				Script: &batchpb.Runnable_Script{Command: command},
			},
		}},
		ComputeResource: resources,
		MaxRunDuration: &durationpb.Duration{
			Seconds: 3600,
		},
		MaxRetryCount: 2,
	}

	// Tasks are grouped inside a job using TaskGroups.
	taskGroups := []*batchpb.TaskGroup{
		{
			TaskCount: 4,
			TaskSpec:  taskSpec,
		},
	}

	// Policies are used to define on what kind of virtual machines the tasks will run on.
	// In this case, we tell the system to use "e2-standard-4" machine type.
	// Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
	allocationPolicy := &batchpb.AllocationPolicy{
		Instances: []*batchpb.AllocationPolicy_InstancePolicyOrTemplate{{
			PolicyTemplate: &batchpb.AllocationPolicy_InstancePolicyOrTemplate_Policy{
				Policy: &batchpb.AllocationPolicy_InstancePolicy{
					MachineType: "e2-standard-4",
				},
			},
		}},
	}

	// We use Cloud Logging as it's an out of the box available option
	logsPolicy := &batchpb.LogsPolicy{
		Destination: batchpb.LogsPolicy_CLOUD_LOGGING,
	}

	jobLabels := map[string]string{"env": "testing", "type": "script"}

	// The job's parent is the region in which the job will run
	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, region)

	job := batchpb.Job{
		TaskGroups:       taskGroups,
		AllocationPolicy: allocationPolicy,
		Labels:           jobLabels,
		LogsPolicy:       logsPolicy,
	}

	req := &batchpb.CreateJobRequest{
		Parent: parent,
		JobId:  jobName,
		Job:    &job,
	}

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

	fmt.Fprintf(w, "Job created: %v\n", created_job)

	return nil
}

Java

Java

詳情請參閱 Batch Java API 參考說明文件

如要向 Batch 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import com.google.cloud.batch.v1.AllocationPolicy;
import com.google.cloud.batch.v1.AllocationPolicy.InstancePolicy;
import com.google.cloud.batch.v1.AllocationPolicy.InstancePolicyOrTemplate;
import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.ComputeResource;
import com.google.cloud.batch.v1.CreateJobRequest;
import com.google.cloud.batch.v1.Job;
import com.google.cloud.batch.v1.LogsPolicy;
import com.google.cloud.batch.v1.LogsPolicy.Destination;
import com.google.cloud.batch.v1.Runnable;
import com.google.cloud.batch.v1.Runnable.Script;
import com.google.cloud.batch.v1.TaskGroup;
import com.google.cloud.batch.v1.TaskSpec;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateWithScriptNoMounting {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // 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 you want to use to run the job. Regions that are
    // available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
    String region = "europe-central2";

    // The name of the job that will be created.
    // It needs to be unique for each project and region pair.
    String jobName = "JOB_NAME";

    createScriptJob(projectId, region, jobName);
  }

  // This method shows how to create a sample Batch Job that will run
  // a simple command on Cloud Compute instances.
  public static void createScriptJob(String projectId, String region, String jobName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // 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()) {

      // Define what will be done as part of the job.
      Runnable runnable =
          Runnable.newBuilder()
              .setScript(
                  Script.newBuilder()
                      .setText(
                          "echo Hello world! This is task ${BATCH_TASK_INDEX}. "
                              + "This job has a total of ${BATCH_TASK_COUNT} tasks.")
                      // You can also run a script from a file. Just remember, that needs to be a
                      // script that's already on the VM that will be running the job.
                      // Using setText() and setPath() is mutually exclusive.
                      // .setPath("/tmp/test.sh")
                      .build())
              .build();

      // We can specify what resources are requested by each task.
      ComputeResource computeResource =
          ComputeResource.newBuilder()
              // In milliseconds per cpu-second. This means the task requires 2 whole CPUs.
              .setCpuMilli(2000)
              // In MiB.
              .setMemoryMib(16)
              .build();

      TaskSpec task =
          TaskSpec.newBuilder()
              // Jobs can be divided into tasks. In this case, we have only one task.
              .addRunnables(runnable)
              .setComputeResource(computeResource)
              .setMaxRetryCount(2)
              .setMaxRunDuration(Duration.newBuilder().setSeconds(3600).build())
              .build();

      // Tasks are grouped inside a job using TaskGroups.
      // Currently, it's possible to have only one task group.
      TaskGroup taskGroup = TaskGroup.newBuilder().setTaskCount(4).setTaskSpec(task).build();

      // Policies are used to define on what kind of virtual machines the tasks will run on.
      // In this case, we tell the system to use "e2-standard-4" machine type.
      // Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
      InstancePolicy instancePolicy =
          InstancePolicy.newBuilder().setMachineType("e2-standard-4").build();

      AllocationPolicy allocationPolicy =
          AllocationPolicy.newBuilder()
              .addInstances(InstancePolicyOrTemplate.newBuilder().setPolicy(instancePolicy).build())
              .build();

      Job job =
          Job.newBuilder()
              .addTaskGroups(taskGroup)
              .setAllocationPolicy(allocationPolicy)
              .putLabels("env", "testing")
              .putLabels("type", "script")
              // We use Cloud Logging as it's an out of the box available option.
              .setLogsPolicy(
                  LogsPolicy.newBuilder().setDestination(Destination.CLOUD_LOGGING).build())
              .build();

      CreateJobRequest createJobRequest =
          CreateJobRequest.newBuilder()
              // The job's parent is the region in which the job will run.
              .setParent(String.format("projects/%s/locations/%s", projectId, region))
              .setJob(job)
              .setJobId(jobName)
              .build();

      Job result =
          batchServiceClient
              .createJobCallable()
              .futureCall(createJobRequest)
              .get(5, TimeUnit.MINUTES);

      System.out.printf("Successfully created the job: %s", result.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 you want to the job to run in. The regions that support Batch are listed here:
 * https://cloud.google.com/batch/docs/get-started#locations
 */
// const region = 'us-central-1';
/**
 * The name of the job that will be created.
 * It needs to be unique for each project and region pair.
 */
// const jobName = 'YOUR_JOB_NAME';

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

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

// Define what will be done as part of the job.
const task = new batch.TaskSpec();
const runnable = new batch.Runnable();
runnable.script = new batch.Runnable.Script();
runnable.script.text =
  'echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks.';
// You can also run a script from a file. Just remember, that needs to be a script that's
// already on the VM that will be running the job. Using runnable.script.text and runnable.script.path is mutually
// exclusive.
// runnable.script.path = '/tmp/test.sh'
task.runnables = [runnable];

// We can specify what resources are requested by each task.
const resources = new batch.ComputeResource();
resources.cpuMilli = 2000; // in milliseconds per cpu-second. This means the task requires 2 whole CPUs.
resources.memoryMib = 16;
task.computeResource = resources;

task.maxRetryCount = 2;
task.maxRunDuration = {seconds: 3600};

// Tasks are grouped inside a job using TaskGroups.
const group = new batch.TaskGroup();
group.taskCount = 4;
group.taskSpec = task;

// Policies are used to define on what kind of virtual machines the tasks will run on.
// In this case, we tell the system to use "e2-standard-4" machine type.
// Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
const allocationPolicy = new batch.AllocationPolicy();
const policy = new batch.AllocationPolicy.InstancePolicy();
policy.machineType = 'e2-standard-4';
const instances = new batch.AllocationPolicy.InstancePolicyOrTemplate();
instances.policy = policy;
allocationPolicy.instances = [instances];

const job = new batch.Job();
job.name = jobName;
job.taskGroups = [group];
job.allocationPolicy = allocationPolicy;
job.labels = {env: 'testing', type: 'script'};
// We use Cloud Logging as it's an option available out of the box
job.logsPolicy = new batch.LogsPolicy();
job.logsPolicy.destination = batch.LogsPolicy.Destination.CLOUD_LOGGING;

// The job's parent is the project and region in which the job will run
const parent = `projects/${projectId}/locations/${region}`;

async function callCreateJob() {
  // Construct request
  const request = {
    parent,
    jobId: jobName,
    job,
  };

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

await callCreateJob();

Python

Python

詳情請參閱 Batch Python API 參考說明文件

如要向 Batch 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from google.cloud import batch_v1


def create_script_job(project_id: str, region: str, job_name: str) -> batch_v1.Job:
    """
    This method shows how to create a sample Batch Job that will run
    a simple command on Cloud Compute instances.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        region: name of the region you want to use to run the job. Regions that are
            available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
        job_name: the name of the job that will be created.
            It needs to be unique for each project and region pair.

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

    # Define what will be done as part of the job.
    task = batch_v1.TaskSpec()
    runnable = batch_v1.Runnable()
    runnable.script = batch_v1.Runnable.Script()
    runnable.script.text = "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
    # You can also run a script from a file. Just remember, that needs to be a script that's
    # already on the VM that will be running the job. Using runnable.script.text and runnable.script.path is mutually
    # exclusive.
    # runnable.script.path = '/tmp/test.sh'
    task.runnables = [runnable]

    # We can specify what resources are requested by each task.
    resources = batch_v1.ComputeResource()
    resources.cpu_milli = 2000  # in milliseconds per cpu-second. This means the task requires 2 whole CPUs.
    resources.memory_mib = 16
    task.compute_resource = resources

    task.max_retry_count = 2
    task.max_run_duration = "3600s"

    # Tasks are grouped inside a job using TaskGroups.
    # Currently, it's possible to have only one task group.
    group = batch_v1.TaskGroup()
    group.task_count = 4
    group.task_spec = task

    # Policies are used to define on what kind of virtual machines the tasks will run on.
    # In this case, we tell the system to use "e2-standard-4" machine type.
    # Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
    allocation_policy = batch_v1.AllocationPolicy()
    policy = batch_v1.AllocationPolicy.InstancePolicy()
    policy.machine_type = "e2-standard-4"
    instances = batch_v1.AllocationPolicy.InstancePolicyOrTemplate()
    instances.policy = policy
    allocation_policy.instances = [instances]

    job = batch_v1.Job()
    job.task_groups = [group]
    job.allocation_policy = allocation_policy
    job.labels = {"env": "testing", "type": "script"}
    # We use Cloud Logging as it's an out of the box available option
    job.logs_policy = batch_v1.LogsPolicy()
    job.logs_policy.destination = batch_v1.LogsPolicy.Destination.CLOUD_LOGGING

    create_request = batch_v1.CreateJobRequest()
    create_request.job = job
    create_request.job_id = job_name
    # The job's parent is the region in which the job will run
    create_request.parent = f"projects/{project_id}/locations/{region}"

    return client.create_job(create_request)

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) {
    // Initialize the request; start with the fields that depend on the sample
    // input.
    google::cloud::batch::v1::CreateJobRequest request;
    request.set_parent("projects/" + project_id + "/locations/" + location_id);
    request.set_job_id(job_id);
    // Most of the job description is fixed in this example; use a string to
    // initialize it.
    auto constexpr kText = R"pb(
      task_groups {
        task_count: 4
        task_spec {
          compute_resource { cpu_milli: 500 memory_mib: 16 }
          max_retry_count: 2
          max_run_duration { seconds: 3600 }
          runnables {
            script {
              text: "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
            }
          }
        }
      }
      allocation_policy {
        instances {
          policy { machine_type: "e2-standard-4" provisioning_model: STANDARD }
        }
      }
      labels { key: "env" value: "testing" }
      labels { key: "type" value: "script" }
      logs_policy { destination: CLOUD_LOGGING }
    )pb";
    auto* job = request.mutable_job();
    if (!google::protobuf::TextFormat::ParseFromString(kText, job)) {
      throw std::runtime_error("Error parsing Job description");
    }
    // Create a client and issue the request.
    auto client = google::cloud::batch_v1::BatchServiceClient(
        google::cloud::batch_v1::MakeBatchServiceConnection());
    auto response = client.CreateJob(request);
    if (!response) throw std::move(response).status();
    std::cout << "Job : " << response->DebugString() << "\n";
  }

使用環境變數

編寫要讓工作執行的容器映像檔或指令碼時,請使用環境變數。您可以使用為所有 Batch 工作預先定義的任何環境變數,以及在建立工作時定義的任何自訂環境變數。

使用預先定義的環境變數

根據預設,作業中的可執行檔可以使用下列預先定義的環境變數:

  • BATCH_TASK_COUNT:這個工作群組中的工作總數。
  • BATCH_TASK_INDEX:這項工作在工作群組中的索引編號。第一個工作的索引是 0,每個額外工作都會遞增。
  • BATCH_HOSTS_FILE:列出這個工作群組中所有執行中 VM 執行個體的檔案路徑。如要使用這個環境變數,requireHostsFile 欄位必須設為 true
  • BATCH_TASK_RETRY_ATTEMPT:這項工作已嘗試的次數。工作第一次嘗試時,值為 0,每次重試時都會遞增。工作允許的重試總次數取決於 maxRetryCount 欄位的值,如果未定義,則為 0。如要進一步瞭解重試,請參閱「自動重試工作」。

如要查看如何使用預先定義的環境變數,請參閱本文件「建立基本工作」中的前一個範例可執行檔。

定義及使用自訂環境變數

您也可以在工作中定義一或多個自訂環境變數。

您可根據資料的所需範圍,在特定環境中定義每個變數:

在所選環境中,您可以使用下列其中一個環境子欄位,定義每個變數的名稱和值:

您可以使用 gcloud CLI 或 Batch API,為工作定義及使用自訂環境變數。以下範例說明如何建立兩個工作,定義及使用標準變數。第一個範例工作含有特定可執行檔的變數。 第二個範例作業具有陣列變數,每個工作的值都不同。

gcloud

如要定義將環境變數傳遞至可執行檔的作業,供每個工作執行,請參閱定義及使用可執行檔的環境變數範例。否則,如要定義工作,根據工作索引將環境變數清單傳遞至不同工作,請參閱為每個工作定義及使用環境變數的範例。

定義及使用可執行檔的環境變數

如要建立工作,並使用 gcloud CLI 將環境變數傳遞至可執行的項目,請使用 gcloud batch jobs submit 指令,並在工作的設定檔中指定環境變數。

舉例來說,如要建立指令碼工作,定義環境變數並傳遞至 3 項工作的指令碼,請提出下列要求:

  1. 在目前目錄中建立名為 hello-world-environment-variables.json 的 JSON 檔案,並加入下列內容:

    {
        "taskGroups": [
            {
                "taskSpec": {
                    "runnables": [
                        {
                            "script": {
                                "text": "echo Hello ${VARIABLE_NAME}! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
                            },
                            "environment": {
                                "variables": {
                                    "VARIABLE_NAME": "VARIABLE_VALUE"
                                }
                            }
                        }
                    ],
                    "computeResource": {
                        "cpuMilli": 2000,
                        "memoryMib": 16
                    }
                },
                "taskCount": 3,
                "parallelism": 1
            }
        ],
        "allocationPolicy": {
            "instances": [
                {
                    "policy": {
                        "machineType": "e2-standard-4"
                    }
                }
            ]
        }
    }
    

    更改下列內容:

    • VARIABLE_NAME:傳遞至各項工作的環境變數名稱。按照慣例,環境變數名稱會大寫
    • VARIABLE_VALUE:選用。傳遞至每個工作的環境變數值。
  2. 執行下列指令:

    gcloud batch jobs submit example-environment-variables-job \
      --location us-central1 \
      --config hello-world-environment-variables.json
    

為每個工作定義及使用環境變數

如要使用 gcloud CLI 建立工作,並根據工作索引將環境變數傳遞至工作,請使用 gcloud batch jobs submit 指令,並在工作的設定檔中指定 taskEnvironments 陣列欄位。

舉例來說,如要建立工作,其中包含 3 個環境變數的陣列,這些變數具有相符的名稱和不同的值,並將環境變數傳遞至工作指令碼,而這些指令碼的索引與陣列中環境變數的索引相符,請執行下列操作:

  1. 在目前目錄中建立名為 hello-world-task-environment-variables.json 的 JSON 檔案,並加入下列內容:

    {
        "taskGroups": [
            {
                "taskSpec": {
                    "runnables": [
                        {
                            "script": {
                                "text": "echo Hello ${TASK_VARIABLE_NAME}! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
                            },
                        }
                    ],
                    "computeResource": {
                        "cpuMilli": 2000,
                        "memoryMib": 16
                    }
                },
                "taskCount": 3,
                "taskEnvironments": [
                    {
                        "variables": {
                            "TASK_VARIABLE_NAME": "TASK_VARIABLE_VALUE_0"
                        }
                    },
                    {
                        "variables": {
                            "TASK_VARIABLE_NAME": "TASK_VARIABLE_VALUE_1"
                        }
                    },
                    {
                        "variables": {
                            "TASK_VARIABLE_NAME": "TASK_VARIABLE_VALUE_2"
                        }
                    }
                ]
            }
        ],
        "allocationPolicy": {
            "instances": [
                {
                    "policy": {
                        "machineType": "e2-standard-4"
                    }
                }
            ]
        }
    }
    

    更改下列內容:

    • TASK_VARIABLE_NAME:傳遞至具有相符索引的工作的工作環境變數名稱。按照慣例,環境變數名稱會大寫
    • TASK_VARIABLE_VALUE_0:傳遞至第一個工作的環境變數值,其中 BATCH_TASK_INDEX 等於 0
    • TASK_VARIABLE_VALUE_1:傳遞至第二項工作的環境變數值,其中 BATCH_TASK_INDEX 等於 1
    • TASK_VARIABLE_VALUE_2:傳遞至第三項工作的環境變數值,其中 BATCH_TASK_INDEX 等於 2
  2. 執行下列指令:

    gcloud batch jobs submit example-task-environment-variables-job \
      --location us-central1 \
      --config hello-world-task-environment-variables.json
    

API

如要定義將環境變數傳遞至可執行檔的作業,供每個工作執行,請參閱定義及使用可執行檔的環境變數範例。否則,如要定義工作,根據工作索引將環境變數清單傳遞至不同工作,請參閱為每個工作定義及使用環境變數的範例。

定義及使用可執行檔的環境變數

如要使用 Batch API 建立工作,並將環境變數傳遞至可執行的項目,請使用 gcloud batch jobs submit 指令,並在 environment 欄位中指定環境變數。

舉例來說,如要建立包含環境變數的工作,並將該變數傳遞至 3 項工作的指令碼,請提出下列要求:

POST https://batch.googleapis.com/v1/projects/<var>PROJECT_ID</var>/locations/us-central1/jobs?job_id=example-environment-variables-job

{
    "taskGroups": [
        {
            "taskSpec": {
                "runnables": [
                    {
                        "script": {
                            "text": "echo Hello ${VARIABLE_NAME}! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
                        },
                        "environment": {
                            "variables": {
                                "VARIABLE_NAME": "VARIABLE_VALUE"
                            }
                        }
                    }
                ],
                "computeResource": {
                    "cpuMilli": 2000,
                    "memoryMib": 16
                }
            },
            "taskCount": 3,
            "parallelism": 1
        }

    ],
    "allocationPolicy": {
        "instances": [
            {
                "policy": {
                    "machineType": "e2-standard-4"
                }
            }
        ]
    }
}

更改下列內容:

  • PROJECT_ID:專案的專案 ID
  • VARIABLE_NAME:傳遞至各項工作的環境變數名稱。按照慣例,環境變數名稱會大寫
  • VARIABLE_VALUE:傳遞至每個工作的環境變數值。

為每個工作定義及使用環境變數

如要使用 Batch API 建立工作,根據工作索引將環境變數傳遞至工作,請使用 jobs.create 方法,並在 taskEnvironments 陣列欄位中指定環境變數。

舉例來說,如要建立工作,其中包含名稱相符但值不同的 3 個環境變數陣列,並根據索引將環境變數傳遞至 3 項工作的指令碼,請提出下列要求:

POST https://batch.googleapis.com/v1/projects/<var>PROJECT_ID</var>/locations/us-central1/jobs?job_id=example-task-environment-variables-job

{
    "taskGroups": [
        {
            "taskSpec": {
                "runnables": [
                    {
                        "script": {
                            "text": "echo Hello ${TASK_VARIABLE_NAME}! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
                        },
                    }
                ],
                "computeResource": {
                    "cpuMilli": 2000,
                    "memoryMib": 16
                }
            },
            "taskCount": 3,
            "taskEnvironments": [
                {
                    "variables": {
                        "TASK_VARIABLE_NAME": "TASK_VARIABLE_VALUE_0"
                    }
                },
                {
                    "variables": {
                        "TASK_VARIABLE_NAME": "TASK_VARIABLE_VALUE_1"
                    }
                },
                {
                    "variables": {
                        "TASK_VARIABLE_NAME": "TASK_VARIABLE_VALUE_2"
                    }
                }
            ]
        }
    ],
    "allocationPolicy": {
        "instances": [
            {
                "policy": { "machineType": "e2-standard-4" }
            }
        ]
    }
}

更改下列內容:

  • PROJECT_ID:專案的專案 ID
  • TASK_VARIABLE_NAME:傳遞至具有相符索引的工作的環境變數名稱。按照慣例,環境變數名稱會大寫
  • TASK_VARIABLE_VALUE_0:傳遞至第一個工作的環境變數值,其中 BATCH_TASK_INDEX 等於 0
  • TASK_VARIABLE_VALUE_1:傳遞至第二項工作的環境變數值,其中 BATCH_TASK_INDEX 等於 1
  • TASK_VARIABLE_VALUE_2:傳遞至第三項工作的環境變數值,其中 BATCH_TASK_INDEX 等於 2

後續步驟