

文档 AWS SDK 示例 GitHub 存储库中还有更多 [S AWS DK 示例](https://github.com/awsdocs/aws-doc-sdk-examples)。

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# AWS Batch 使用的操作 AWS SDKs
<a name="batch_code_examples_actions"></a>

以下代码示例演示了如何使用执行单个 AWS Batch 操作 AWS SDKs。每个示例都包含一个指向的链接 GitHub，您可以在其中找到有关设置和运行代码的说明。

这些摘录调用 AWS Batch API，是大型程序的代码摘录，这些程序必须在上下文中运行。您可以在[AWS Batch 使用场景 AWS SDKs](batch_code_examples_scenarios.md)中结合上下文查看操作。

 以下示例仅包括最常用的操作。有关完整列表，请参阅 [AWS Batch API 参考](https://docs.aws.amazon.com/batch/latest/APIReference/Welcome.html)。

**Topics**
+ [`CreateComputeEnvironment`](batch_example_batch_CreateComputeEnvironment_section.md)
+ [`CreateJobQueue`](batch_example_batch_CreateJobQueue_section.md)
+ [`DeleteComputeEnvironment`](batch_example_batch_DeleteComputeEnvironment_section.md)
+ [`DeleteJobQueue`](batch_example_batch_DeleteJobQueue_section.md)
+ [`DeregisterJobDefinition`](batch_example_batch_DeregisterJobDefinition_section.md)
+ [`DescribeComputeEnvironments`](batch_example_batch_DescribeComputeEnvironments_section.md)
+ [`DescribeJobQueues`](batch_example_batch_DescribeJobQueues_section.md)
+ [`DescribeJobs`](batch_example_batch_DescribeJobs_section.md)
+ [`ListJobsPaginator`](batch_example_batch_ListJobsPaginator_section.md)
+ [`RegisterJobDefinition`](batch_example_batch_RegisterJobDefinition_section.md)
+ [`SubmitJob`](batch_example_batch_SubmitJob_section.md)
+ [`UpdateComputeEnvironment`](batch_example_batch_UpdateComputeEnvironment_section.md)
+ [`UpdateJobQueue`](batch_example_batch_UpdateJobQueue_section.md)

# `CreateComputeEnvironment`与 AWS SDK 或 CLI 配合使用
<a name="batch_example_batch_CreateComputeEnvironment_section"></a>

以下代码示例演示如何使用 `CreateComputeEnvironment`。

操作示例是大型程序的代码摘录，必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文：
+  [了解基本功能](batch_example_batch_Scenario_section.md) 
+  [Batch 和 Fargate 入门](batch_example_fargate_GettingStarted_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**创建具有按需型实例的托管计算环境**  
此示例创建一个托管计算环境，具有按需启动的特定 C4 实例类型。计算环境称为 C4 OnDemand。  
命令:  

```
aws batch create-compute-environment --cli-input-json file://<path_to_json_file>/C4OnDemand.json
```
JSON 文件格式：  

```
{
  "computeEnvironmentName": "C4OnDemand",
  "type": "MANAGED",
  "state": "ENABLED",
  "computeResources": {
    "type": "EC2",
    "minvCpus": 0,
    "maxvCpus": 128,
    "desiredvCpus": 48,
    "instanceTypes": [
      "c4.large",
      "c4.xlarge",
      "c4.2xlarge",
      "c4.4xlarge",
      "c4.8xlarge"
    ],
    "subnets": [
      "subnet-220c0e0a",
      "subnet-1a95556d",
      "subnet-978f6dce"
    ],
    "securityGroupIds": [
      "sg-cf5093b2"
    ],
    "ec2KeyPair": "id_rsa",
    "instanceRole": "ecsInstanceRole",
    "tags": {
      "Name": "Batch Instance - C4OnDemand"
    }
  },
  "serviceRole": "arn:aws:iam::012345678910:role/AWSBatchServiceRole"
}
```
输出：  

```
{
    "computeEnvironmentName": "C4OnDemand",
    "computeEnvironmentArn": "arn:aws:batch:us-east-1:012345678910:compute-environment/C4OnDemand"
}
```
**创建具有竞价型实例托管计算环境**  
此示例创建一个具有 M4 实例类型的托管计算环境，在竞价出价等于或低于该实例类型按需价格的 20% 时启动。计算环境称为 M4Spot。  
命令:  

```
aws batch create-compute-environment --cli-input-json file://<path_to_json_file>/M4Spot.json
```
JSON 文件格式：  

```
{
  "computeEnvironmentName": "M4Spot",
  "type": "MANAGED",
  "state": "ENABLED",
  "computeResources": {
    "type": "SPOT",
    "spotIamFleetRole": "arn:aws:iam::012345678910:role/aws-ec2-spot-fleet-role",
    "minvCpus": 0,
    "maxvCpus": 128,
    "desiredvCpus": 4,
    "instanceTypes": [
      "m4"
    ],
    "bidPercentage": 20,
    "subnets": [
      "subnet-220c0e0a",
      "subnet-1a95556d",
      "subnet-978f6dce"
    ],
    "securityGroupIds": [
      "sg-cf5093b2"
    ],
    "ec2KeyPair": "id_rsa",
    "instanceRole": "ecsInstanceRole",
    "tags": {
      "Name": "Batch Instance - M4Spot"
    }
  },
  "serviceRole": "arn:aws:iam::012345678910:role/AWSBatchServiceRole"
}
```
输出：  

```
{
    "computeEnvironmentName": "M4Spot",
    "computeEnvironmentArn": "arn:aws:batch:us-east-1:012345678910:compute-environment/M4Spot"
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[CreateComputeEnvironment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/create-compute-environment.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Asynchronously creates a new compute environment in AWS Batch.
     *
     * @param computeEnvironmentName the name of the compute environment to create
     * @param batchIAMRole the IAM role to be used by the compute environment
     * @param subnet the subnet ID to be used for the compute environment
     * @param secGroup the security group ID to be used for the compute environment
     * @return a {@link CompletableFuture} representing the asynchronous operation, which will complete with the
     *         {@link CreateComputeEnvironmentResponse} when the compute environment has been created
     * @throws BatchException if there is an error creating the compute environment
     * @throws RuntimeException if there is an unexpected error during the operation
     */
    public CompletableFuture<CreateComputeEnvironmentResponse> createComputeEnvironmentAsync(
        String computeEnvironmentName, String batchIAMRole, String subnet, String secGroup) {
        CreateComputeEnvironmentRequest environmentRequest = CreateComputeEnvironmentRequest.builder()
            .computeEnvironmentName(computeEnvironmentName)
            .type(CEType.MANAGED)
            .state(CEState.ENABLED)
            .computeResources(ComputeResource.builder()
                .type(CRType.FARGATE)
                .maxvCpus(256)
                .subnets(Collections.singletonList(subnet))
                .securityGroupIds(Collections.singletonList(secGroup))
                .build())
            .serviceRole(batchIAMRole)
            .build();

        CompletableFuture<CreateComputeEnvironmentResponse> response = getAsyncClient().createComputeEnvironment(environmentRequest);
        response.whenComplete((resp, ex) -> {
            if (ex != null) {
               String errorMessage = "Unexpected error occurred: " + ex.getMessage();
               throw new RuntimeException(errorMessage, ex);
            }
        });

        return response;
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[CreateComputeEnvironment](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/CreateComputeEnvironment)*中的。

------

# `CreateJobQueue`与 AWS SDK 或 CLI 配合使用
<a name="batch_example_batch_CreateJobQueue_section"></a>

以下代码示例演示如何使用 `CreateJobQueue`。

操作示例是大型程序的代码摘录，必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文：
+  [了解基本功能](batch_example_batch_Scenario_section.md) 
+  [Batch 和 Fargate 入门](batch_example_fargate_GettingStarted_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**创建包含单一计算环境的低优先级作业队列**  
此示例创建了一个名为的作业队列 LowPriority ，该队列使用 M4Spot 计算环境。  
命令:  

```
aws batch create-job-queue --cli-input-json file://<path_to_json_file>/LowPriority.json
```
JSON 文件格式：  

```
{
  "jobQueueName": "LowPriority",
  "state": "ENABLED",
  "priority": 10,
  "computeEnvironmentOrder": [
    {
      "order": 1,
      "computeEnvironment": "M4Spot"
    }
  ]
}
```
输出：  

```
{
    "jobQueueArn": "arn:aws:batch:us-east-1:012345678910:job-queue/LowPriority",
    "jobQueueName": "LowPriority"
}
```
**创建包含两个计算环境的高优先级作业队列**  
此示例创建了一个名为的作业队列 HighPriority ，该队列使用阶数为 1 的 C4 OnDemand 计算环境和阶数为 2 的 M4Spot 计算环境。调度器将首先尝试在 C4 OnDemand 计算环境中放置作业。  
命令:  

```
aws batch create-job-queue --cli-input-json file://<path_to_json_file>/HighPriority.json
```
JSON 文件格式：  

```
{
  "jobQueueName": "HighPriority",
  "state": "ENABLED",
  "priority": 1,
  "computeEnvironmentOrder": [
    {
      "order": 1,
      "computeEnvironment": "C4OnDemand"
    },
    {
      "order": 2,
      "computeEnvironment": "M4Spot"
    }
  ]
}
```
输出：  

```
{
    "jobQueueArn": "arn:aws:batch:us-east-1:012345678910:job-queue/HighPriority",
    "jobQueueName": "HighPriority"
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[CreateJobQueue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/create-job-queue.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Creates a job queue asynchronously.
     *
     * @param jobQueueName the name of the job queue to create
     * @param computeEnvironmentName the name of the compute environment to associate with the job queue
     * @return a CompletableFuture that completes with the Amazon Resource Name (ARN) of the job queue
     */
    public CompletableFuture<String> createJobQueueAsync(String jobQueueName, String computeEnvironmentName) {
        if (jobQueueName == null || jobQueueName.isEmpty()) {
            throw new IllegalArgumentException("Job queue name cannot be null or empty");
        }
        if (computeEnvironmentName == null || computeEnvironmentName.isEmpty()) {
            throw new IllegalArgumentException("Compute environment name cannot be null or empty");
        }

        CreateJobQueueRequest request = CreateJobQueueRequest.builder()
            .jobQueueName(jobQueueName)
            .priority(1)
            .computeEnvironmentOrder(ComputeEnvironmentOrder.builder()
                .computeEnvironment(computeEnvironmentName)
                .order(1)
                .build())
            .build();

        CompletableFuture<CreateJobQueueResponse> response = getAsyncClient().createJobQueue(request);
        response.whenComplete((resp, ex) -> {
            if (ex != null) {
                String errorMessage = "Unexpected error occurred: " + ex.getMessage();
                throw new RuntimeException(errorMessage, ex);
            }
        });

        return response.thenApply(CreateJobQueueResponse::jobQueueArn);
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[CreateJobQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/CreateJobQueue)*中的。

------

# `DeleteComputeEnvironment`与 AWS SDK 或 CLI 配合使用
<a name="batch_example_batch_DeleteComputeEnvironment_section"></a>

以下代码示例演示如何使用 `DeleteComputeEnvironment`。

操作示例是大型程序的代码摘录，必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文：
+  [了解基本功能](batch_example_batch_Scenario_section.md) 
+  [Batch 和 Fargate 入门](batch_example_fargate_GettingStarted_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**删除计算环境**  
此示例删除了 P2 OnDemand 计算环境。  
命令:  

```
aws batch delete-compute-environment --compute-environment P2OnDemand
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DeleteComputeEnvironment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/delete-compute-environment.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public CompletableFuture<DeleteComputeEnvironmentResponse> deleteComputeEnvironmentAsync(String computeEnvironmentName) {
        DeleteComputeEnvironmentRequest deleteComputeEnvironment = DeleteComputeEnvironmentRequest.builder()
            .computeEnvironment(computeEnvironmentName)
            .build();

        return getAsyncClient().deleteComputeEnvironment(deleteComputeEnvironment)
            .whenComplete((response, ex) -> {
                if (ex != null) {
                    Throwable cause = ex.getCause();
                    if (cause instanceof BatchException) {
                        throw new RuntimeException(cause);
                    } else {
                        throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
                    }
                }
            });
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[DeleteComputeEnvironment](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/DeleteComputeEnvironment)*中的。

------

# `DeleteJobQueue`与 AWS SDK 或 CLI 配合使用
<a name="batch_example_batch_DeleteJobQueue_section"></a>

以下代码示例演示如何使用 `DeleteJobQueue`。

操作示例是大型程序的代码摘录，必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文：
+  [了解基本功能](batch_example_batch_Scenario_section.md) 
+  [Batch 和 Fargate 入门](batch_example_fargate_GettingStarted_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**删除作业队列**  
此示例删除 GPGPU 作业队列。  
命令:  

```
aws batch delete-job-queue --job-queue GPGPU
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DeleteJobQueue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/delete-job-queue.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Deletes a Batch job queue asynchronously.
     *
     * @param jobQueueArn The Amazon Resource Name (ARN) of the job queue to delete.
     * @return A CompletableFuture that represents the asynchronous deletion of the job queue.
     *         The future completes when the job queue has been successfully deleted or if an error occurs.
     *         If successful, the future will be completed with a {@code Void} value.
     *         If an error occurs, the future will be completed exceptionally with the thrown exception.
     */
    public CompletableFuture<Void> deleteJobQueueAsync(String jobQueueArn) {
        DeleteJobQueueRequest deleteRequest = DeleteJobQueueRequest.builder()
            .jobQueue(jobQueueArn)
            .build();

        CompletableFuture<DeleteJobQueueResponse> responseFuture = getAsyncClient().deleteJobQueue(deleteRequest);
        return responseFuture.whenComplete((deleteResponse, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to delete job queue: " + ex.getMessage(), ex);
            }
        }).thenApply(deleteResponse -> null);
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[DeleteJobQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/DeleteJobQueue)*中的。

------

# `DeregisterJobDefinition`与 AWS SDK 或 CLI 配合使用
<a name="batch_example_batch_DeregisterJobDefinition_section"></a>

以下代码示例演示如何使用 `DeregisterJobDefinition`。

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [了解基本功能](batch_example_batch_Scenario_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**注销作业定义**  
此示例注销名为 sleep10 的作业定义。  
命令:  

```
aws batch deregister-job-definition --job-definition sleep10
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DeregisterJobDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/deregister-job-definition.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Deregisters a job definition asynchronously.
     *
     * @param jobDefinition the name of the job definition to be deregistered
     * @return a CompletableFuture that completes when the job definition has been deregistered
     * or an exception has occurred
     */
    public CompletableFuture<DeregisterJobDefinitionResponse> deregisterJobDefinitionAsync(String jobDefinition) {
        DeregisterJobDefinitionRequest jobDefinitionRequest = DeregisterJobDefinitionRequest.builder()
            .jobDefinition(jobDefinition)
            .build();

        CompletableFuture<DeregisterJobDefinitionResponse> responseFuture = getAsyncClient().deregisterJobDefinition(jobDefinitionRequest);
        responseFuture.whenComplete((response, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Unexpected error occurred: " + ex.getMessage(), ex);
            }
        });

        return responseFuture;
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[DeregisterJobDefinition](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/DeregisterJobDefinition)*中的。

------

# `DescribeComputeEnvironments`与 AWS SDK 或 CLI 配合使用
<a name="batch_example_batch_DescribeComputeEnvironments_section"></a>

以下代码示例演示如何使用 `DescribeComputeEnvironments`。

操作示例是大型程序的代码摘录，必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文：
+  [了解基本功能](batch_example_batch_Scenario_section.md) 
+  [Batch 和 Fargate 入门](batch_example_fargate_GettingStarted_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**描述计算环境**  
此示例描述了 P2 OnDemand 计算环境。  
命令:  

```
aws batch describe-compute-environments --compute-environments P2OnDemand
```
输出：  

```
{
    "computeEnvironments": [
        {
            "status": "VALID",
            "serviceRole": "arn:aws:iam::012345678910:role/AWSBatchServiceRole",
            "computeEnvironmentArn": "arn:aws:batch:us-east-1:012345678910:compute-environment/P2OnDemand",
            "computeResources": {
                "subnets": [
                    "subnet-220c0e0a",
                    "subnet-1a95556d",
                    "subnet-978f6dce"
                ],
                "tags": {
                    "Name": "Batch Instance - P2OnDemand"
                },
                "desiredvCpus": 48,
                "minvCpus": 0,
                "instanceTypes": [
                    "p2"
                ],
                "securityGroupIds": [
                    "sg-cf5093b2"
                ],
                "instanceRole": "ecsInstanceRole",
                "maxvCpus": 128,
                "type": "EC2",
                "ec2KeyPair": "id_rsa"
            },
            "statusReason": "ComputeEnvironment Healthy",
            "ecsClusterArn": "arn:aws:ecs:us-east-1:012345678910:cluster/P2OnDemand_Batch_2c06f29d-d1fe-3a49-879d-42394c86effc",
            "state": "ENABLED",
            "computeEnvironmentName": "P2OnDemand",
            "type": "MANAGED"
        }
    ]
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeComputeEnvironments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/describe-compute-environments.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Checks the status of the specified compute environment.
     *
     * @param computeEnvironmentName the name of the compute environment to check
     * @return a CompletableFuture containing the status of the compute environment, or "ERROR" if an exception occurs
     */
    public CompletableFuture<String> checkComputeEnvironmentsStatus(String computeEnvironmentName) {
        if (computeEnvironmentName == null || computeEnvironmentName.isEmpty()) {
            throw new IllegalArgumentException("Compute environment name cannot be null or empty");
        }

        DescribeComputeEnvironmentsRequest environmentsRequest = DescribeComputeEnvironmentsRequest.builder()
            .computeEnvironments(computeEnvironmentName)
            .build();

        CompletableFuture<DescribeComputeEnvironmentsResponse> response = getAsyncClient().describeComputeEnvironments(environmentsRequest);
        response.whenComplete((resp, ex) -> {
            if (ex != null) {
                String errorMessage = "Unexpected error occurred: " + ex.getMessage();
                throw new RuntimeException(errorMessage, ex);
            }
        });

        return response.thenApply(resp -> resp.computeEnvironments().stream()
            .map(env -> env.statusAsString())
            .findFirst()
            .orElse("UNKNOWN"));
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[DescribeComputeEnvironments](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/DescribeComputeEnvironments)*中的。

------

# `DescribeJobQueues`与 AWS SDK 或 CLI 配合使用
<a name="batch_example_batch_DescribeJobQueues_section"></a>

以下代码示例演示如何使用 `DescribeJobQueues`。

操作示例是大型程序的代码摘录，必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文：
+  [了解基本功能](batch_example_batch_Scenario_section.md) 
+  [Batch 和 Fargate 入门](batch_example_fargate_GettingStarted_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**描述作业队列**  
此示例描述了 HighPriority 任务队列。  
命令:  

```
aws batch describe-job-queues --job-queues HighPriority
```
输出：  

```
{
    "jobQueues": [
        {
            "status": "VALID",
            "jobQueueArn": "arn:aws:batch:us-east-1:012345678910:job-queue/HighPriority",
            "computeEnvironmentOrder": [
                {
                    "computeEnvironment": "arn:aws:batch:us-east-1:012345678910:compute-environment/C4OnDemand",
                    "order": 1
                }
            ],
            "statusReason": "JobQueue Healthy",
            "priority": 1,
            "state": "ENABLED",
            "jobQueueName": "HighPriority"
        }
    ]
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeJobQueues](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/describe-job-queues.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Asynchronously describes the job queue associated with the specified compute environment.
     *
     * @param computeEnvironmentName the name of the compute environment to find the associated job queue for
     * @return a {@link CompletableFuture} that, when completed, contains the job queue ARN associated with the specified compute environment
     * @throws RuntimeException if the job queue description fails
     */
    public CompletableFuture<String> describeJobQueueAsync(String computeEnvironmentName) {
        DescribeJobQueuesRequest describeJobQueuesRequest = DescribeJobQueuesRequest.builder()
            .build();

        CompletableFuture<DescribeJobQueuesResponse> responseFuture = getAsyncClient().describeJobQueues(describeJobQueuesRequest);
        return responseFuture.whenComplete((describeJobQueuesResponse, ex) -> {
            if (describeJobQueuesResponse != null) {
                String jobQueueARN;
                for (JobQueueDetail jobQueueDetail : describeJobQueuesResponse.jobQueues()) {
                    for (ComputeEnvironmentOrder computeEnvironmentOrder : jobQueueDetail.computeEnvironmentOrder()) {
                        String computeEnvironment = computeEnvironmentOrder.computeEnvironment();
                        String name = getComputeEnvironmentName(computeEnvironment);
                        if (name.equals(computeEnvironmentName)) {
                            jobQueueARN = jobQueueDetail.jobQueueArn();
                            logger.info("Job queue ARN associated with the compute environment: " + jobQueueARN);
                        }
                    }
                }
            } else {
                throw new RuntimeException("Failed to describe job queue: " + ex.getMessage(), ex);
            }
        }).thenApply(describeJobQueuesResponse -> {
            String jobQueueARN = "";
            for (JobQueueDetail jobQueueDetail : describeJobQueuesResponse.jobQueues()) {
                for (ComputeEnvironmentOrder computeEnvironmentOrder : jobQueueDetail.computeEnvironmentOrder()) {
                    String computeEnvironment = computeEnvironmentOrder.computeEnvironment();
                    String name = getComputeEnvironmentName(computeEnvironment);
                    if (name.equals(computeEnvironmentName)) {
                        jobQueueARN = jobQueueDetail.jobQueueArn();
                    }
                }
            }
            return jobQueueARN;
        });
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[DescribeJobQueues](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/DescribeJobQueues)*中的。

------

# `DescribeJobs`与 AWS SDK 或 CLI 配合使用
<a name="batch_example_batch_DescribeJobs_section"></a>

以下代码示例演示如何使用 `DescribeJobs`。

操作示例是大型程序的代码摘录，必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文：
+  [了解基本功能](batch_example_batch_Scenario_section.md) 
+  [Batch 和 Fargate 入门](batch_example_fargate_GettingStarted_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**描述任务**  
以下 `describe-jobs` 示例描述具有指定作业 ID 的作业。  

```
aws batch describe-jobs \
    --jobs bcf0b186-a532-4122-842e-2ccab8d54efb
```
输出：  

```
{
    "jobs": [
        {
            "status": "SUBMITTED",
            "container": {
                "mountPoints": [],
                "image": "busybox",
                "environment": [],
                "vcpus": 1,
                "command": [
                    "sleep",
                    "60"
                ],
                "volumes": [],
                "memory": 128,
                "ulimits": []
            },
            "parameters": {},
            "jobDefinition": "arn:aws:batch:us-east-1:012345678910:job-definition/sleep60:1",
            "jobQueue": "arn:aws:batch:us-east-1:012345678910:job-queue/HighPriority",
            "jobId": "bcf0b186-a532-4122-842e-2ccab8d54efb",
            "dependsOn": [],
            "jobName": "example",
            "createdAt": 1480483387803
        }
    ]
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/describe-jobs.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Asynchronously retrieves the status of a specific job.
     *
     * @param jobId the ID of the job to retrieve the status for
     * @return a CompletableFuture that completes with the job status
     */
    public CompletableFuture<String> describeJobAsync(String jobId) {
        DescribeJobsRequest describeJobsRequest = DescribeJobsRequest.builder()
            .jobs(jobId)
            .build();

        CompletableFuture<DescribeJobsResponse> responseFuture = getAsyncClient().describeJobs(describeJobsRequest);
        return responseFuture.whenComplete((response, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Unexpected error occurred: " + ex.getMessage(), ex);
            }
        }).thenApply(response -> response.jobs().get(0).status().toString());
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[DescribeJobs](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/DescribeJobs)*中的。

------

# 与 AWS SDK `ListJobsPaginator` 配合使用
<a name="batch_example_batch_ListJobsPaginator_section"></a>

以下代码示例演示了如何使用 `ListJobsPaginator`。

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [了解基本功能](batch_example_batch_Scenario_section.md) 

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Asynchronously lists the jobs in the specified job queue with the given job status.
     *
     * @param jobQueue the name of the job queue to list jobs from
     * @return a List<JobSummary> that contains the jobs that succeeded
     */
    public List<JobSummary> listJobsAsync(String jobQueue) {
        if (jobQueue == null || jobQueue.isEmpty()) {
            throw new IllegalArgumentException("Job queue cannot be null or empty");
        }

        ListJobsRequest listJobsRequest = ListJobsRequest.builder()
            .jobQueue(jobQueue)
            .jobStatus(JobStatus.SUCCEEDED)  // Filter jobs by status.
            .build();

        List<JobSummary> jobSummaries = new ArrayList<>();
        ListJobsPublisher listJobsPaginator = getAsyncClient().listJobsPaginator(listJobsRequest);
        CompletableFuture<Void> future = listJobsPaginator.subscribe(response -> {
            jobSummaries.addAll(response.jobSummaryList());
        });
        future.join();
        return jobSummaries;
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[ListJobsPaginator](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/ListJobsPaginator)*中的。

------

# `RegisterJobDefinition`与 AWS SDK 或 CLI 配合使用
<a name="batch_example_batch_RegisterJobDefinition_section"></a>

以下代码示例演示如何使用 `RegisterJobDefinition`。

操作示例是大型程序的代码摘录，必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文：
+  [了解基本功能](batch_example_batch_Scenario_section.md) 
+  [Batch 和 Fargate 入门](batch_example_fargate_GettingStarted_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**注册作业定义**  
此示例为一个简单容器作业注册作业定义。  
命令:  

```
aws batch register-job-definition --job-definition-name sleep30 --type container --container-properties '{ "image": "busybox", "vcpus": 1, "memory": 128, "command": [ "sleep", "30"]}'
```
输出：  

```
{
    "jobDefinitionArn": "arn:aws:batch:us-east-1:012345678910:job-definition/sleep30:1",
    "jobDefinitionName": "sleep30",
    "revision": 1
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[RegisterJobDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/register-job-definition.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Registers a new job definition asynchronously in AWS Batch.
     * <p>
     * When using Fargate as the compute environment, it is crucial to set the
     * {@link NetworkConfiguration} with {@link AssignPublicIp#ENABLED} to
     * ensure proper networking configuration for the Fargate tasks. This
     * allows the tasks to communicate with external services, access the
     * internet, or communicate within a VPC.
     *
     * @param jobDefinitionName the name of the job definition to be registered
     * @param executionRoleARN the ARN (Amazon Resource Name) of the execution role
     *                         that provides permissions for the containers in the job
     * @param cpuArch a value of either X86_64 or ARM64 required for the service call
     * @return a CompletableFuture that completes with the ARN of the registered
     *         job definition upon successful execution, or completes exceptionally with
     *         an error if the registration fails
     */
    public CompletableFuture<String> registerJobDefinitionAsync(String jobDefinitionName, String executionRoleARN, String image, String cpuArch) {
        NetworkConfiguration networkConfiguration = NetworkConfiguration.builder()
                .assignPublicIp(AssignPublicIp.ENABLED)
                .build();

        ContainerProperties containerProperties = ContainerProperties.builder()
                .image(image)
                .executionRoleArn(executionRoleARN)
                .resourceRequirements(
                        Arrays.asList(
                                ResourceRequirement.builder()
                                        .type(ResourceType.VCPU)
                                        .value("1")
                                        .build(),
                                ResourceRequirement.builder()
                                        .type(ResourceType.MEMORY)
                                        .value("2048")
                                        .build()
                        )
                )
                .networkConfiguration(networkConfiguration)
               .runtimePlatform(b -> b
                        .cpuArchitecture(cpuArch)
                        .operatingSystemFamily("LINUX"))
                .build();

        RegisterJobDefinitionRequest request = RegisterJobDefinitionRequest.builder()
                .jobDefinitionName(jobDefinitionName)
                .type(JobDefinitionType.CONTAINER)
                .containerProperties(containerProperties)
                .platformCapabilities(PlatformCapability.FARGATE)
                .build();

        CompletableFuture<String> future = new CompletableFuture<>();
        getAsyncClient().registerJobDefinition(request)
                .thenApply(RegisterJobDefinitionResponse::jobDefinitionArn)
                .whenComplete((result, ex) -> {
                    if (ex != null) {
                        future.completeExceptionally(ex);
                    } else {
                        future.complete(result);
                    }
                });

        return future;
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[RegisterJobDefinition](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/RegisterJobDefinition)*中的。

------

# `SubmitJob`与 AWS SDK 或 CLI 配合使用
<a name="batch_example_batch_SubmitJob_section"></a>

以下代码示例演示如何使用 `SubmitJob`。

操作示例是大型程序的代码摘录，必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文：
+  [了解基本功能](batch_example_batch_Scenario_section.md) 
+  [Batch 和 Fargate 入门](batch_example_fargate_GettingStarted_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**提交作业**  
此示例向作业队列提交了一个名为 example 的简单容器 HighPriority 作业。  
命令:  

```
aws batch submit-job --job-name example --job-queue HighPriority  --job-definition sleep60
```
输出：  

```
{
    "jobName": "example",
    "jobId": "876da822-4198-45f2-a252-6cea32512ea8"
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[SubmitJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/submit-job.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Submits a job asynchronously to the AWS Batch service.
     *
     * @param jobDefinitionName the name of the job definition to use
     * @param jobQueueName the name of the job queue to submit the job to
     * @param jobARN the Amazon Resource Name (ARN) of the job definition
     * @return a CompletableFuture that, when completed, contains the job ID of the submitted job
     */
    public CompletableFuture<String> submitJobAsync(String jobDefinitionName, String jobQueueName, String jobARN) {
        SubmitJobRequest jobRequest = SubmitJobRequest.builder()
            .jobDefinition(jobARN)
            .jobName(jobDefinitionName)
            .jobQueue(jobQueueName)
            .build();

        CompletableFuture<SubmitJobResponse> responseFuture = getAsyncClient().submitJob(jobRequest);
        responseFuture.whenComplete((response, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Unexpected error occurred: " + ex.getMessage(), ex);
            }
        });

        return responseFuture.thenApply(SubmitJobResponse::jobId);
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[SubmitJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/SubmitJob)*中的。

------

# `UpdateComputeEnvironment`与 AWS SDK 或 CLI 配合使用
<a name="batch_example_batch_UpdateComputeEnvironment_section"></a>

以下代码示例演示如何使用 `UpdateComputeEnvironment`。

操作示例是大型程序的代码摘录，必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文：
+  [了解基本功能](batch_example_batch_Scenario_section.md) 
+  [Batch 和 Fargate 入门](batch_example_fargate_GettingStarted_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**更新计算环境**  
此示例禁用 P2 OnDemand 计算环境，因此可以将其删除。  
命令:  

```
aws batch update-compute-environment --compute-environment P2OnDemand --state DISABLED
```
输出：  

```
{
    "computeEnvironmentName": "P2OnDemand",
    "computeEnvironmentArn": "arn:aws:batch:us-east-1:012345678910:compute-environment/P2OnDemand"
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[UpdateComputeEnvironment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/update-compute-environment.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Disables the specified compute environment asynchronously.
     *
     * @param computeEnvironmentName the name of the compute environment to disable
     * @return a CompletableFuture that completes when the compute environment is disabled
     */
    public CompletableFuture<UpdateComputeEnvironmentResponse> disableComputeEnvironmentAsync(String computeEnvironmentName) {
        UpdateComputeEnvironmentRequest updateRequest = UpdateComputeEnvironmentRequest.builder()
            .computeEnvironment(computeEnvironmentName)
            .state(CEState.DISABLED)
            .build();

        CompletableFuture<UpdateComputeEnvironmentResponse> responseFuture = getAsyncClient().updateComputeEnvironment(updateRequest);
        responseFuture.whenComplete((response, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to disable compute environment: " + ex.getMessage(), ex);
            }
        });

        return responseFuture;
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[UpdateComputeEnvironment](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/UpdateComputeEnvironment)*中的。

------

# `UpdateJobQueue`与 AWS SDK 或 CLI 配合使用
<a name="batch_example_batch_UpdateJobQueue_section"></a>

以下代码示例演示如何使用 `UpdateJobQueue`。

操作示例是大型程序的代码摘录，必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文：
+  [了解基本功能](batch_example_batch_Scenario_section.md) 
+  [Batch 和 Fargate 入门](batch_example_fargate_GettingStarted_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**更新作业队列**  
此示例禁用作业队列，以便将其删除。  
命令:  

```
aws batch update-job-queue --job-queue GPGPU --state DISABLED
```
输出：  

```
{
    "jobQueueArn": "arn:aws:batch:us-east-1:012345678910:job-queue/GPGPU",
    "jobQueueName": "GPGPU"
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[UpdateJobQueue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/update-job-queue.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Disables the specified job queue asynchronously.
     *
     * @param jobQueueArn the Amazon Resource Name (ARN) of the job queue to be disabled
     * @return a {@link CompletableFuture} that completes when the job queue update operation is complete,
     *         or completes exceptionally if an error occurs during the operation
     */
    public CompletableFuture<Void> disableJobQueueAsync(String jobQueueArn) {
        UpdateJobQueueRequest updateRequest = UpdateJobQueueRequest.builder()
            .jobQueue(jobQueueArn)
            .state(JQState.DISABLED)
            .build();

        CompletableFuture<UpdateJobQueueResponse> responseFuture = getAsyncClient().updateJobQueue(updateRequest);
        return responseFuture.whenComplete((updateResponse, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to update job queue: " + ex.getMessage(), ex);
            }
        }).thenApply(updateResponse -> null);
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[UpdateJobQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/UpdateJobQueue)*中的。

------