Share via


BatchClient.CreateTaskCollectionAsync Method

Definition

Overloads

CreateTaskCollectionAsync(String, BatchTaskGroup, Nullable<Int32>, Nullable<DateTimeOffset>, CancellationToken)

Adds a collection of Tasks to the specified Job.

CreateTaskCollectionAsync(String, RequestContent, Nullable<Int32>, Nullable<DateTimeOffset>, RequestContext)

[Protocol Method] Adds a collection of Tasks to the specified Job.

CreateTaskCollectionAsync(String, BatchTaskGroup, Nullable<Int32>, Nullable<DateTimeOffset>, CancellationToken)

Adds a collection of Tasks to the specified Job.

public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Compute.Batch.BatchTaskAddCollectionResult>> CreateTaskCollectionAsync (string jobId, Azure.Compute.Batch.BatchTaskGroup taskCollection, int? timeOutInSeconds = default, DateTimeOffset? ocpdate = default, System.Threading.CancellationToken cancellationToken = default);
abstract member CreateTaskCollectionAsync : string * Azure.Compute.Batch.BatchTaskGroup * Nullable<int> * Nullable<DateTimeOffset> * System.Threading.CancellationToken -> System.Threading.Tasks.Task<Azure.Response<Azure.Compute.Batch.BatchTaskAddCollectionResult>>
override this.CreateTaskCollectionAsync : string * Azure.Compute.Batch.BatchTaskGroup * Nullable<int> * Nullable<DateTimeOffset> * System.Threading.CancellationToken -> System.Threading.Tasks.Task<Azure.Response<Azure.Compute.Batch.BatchTaskAddCollectionResult>>
Public Overridable Function CreateTaskCollectionAsync (jobId As String, taskCollection As BatchTaskGroup, Optional timeOutInSeconds As Nullable(Of Integer) = Nothing, Optional ocpdate As Nullable(Of DateTimeOffset) = Nothing, Optional cancellationToken As CancellationToken = Nothing) As Task(Of Response(Of BatchTaskAddCollectionResult))

Parameters

jobId
String

The ID of the Job to which the Task collection is to be added.

taskCollection
BatchTaskGroup

The Tasks to be added.

timeOutInSeconds
Nullable<Int32>

The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.".

ocpdate
Nullable<DateTimeOffset>

The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly.

cancellationToken
CancellationToken

The cancellation token to use.

Returns

Exceptions

jobId or taskCollection is null.

jobId is an empty string, and was expected to be non-empty.

Examples

This sample shows how to call CreateTaskCollectionAsync.

Uri endpoint = new Uri("<https://my-service.azure.com>");
TokenCredential credential = new DefaultAzureCredential();
BatchClient client = new BatchClient(endpoint, credential);

BatchTaskGroup taskCollection = new BatchTaskGroup(new BatchTaskCreateContent[]
{
    new BatchTaskCreateContent("<id>", "<commandLine>")
});
Response<BatchTaskAddCollectionResult> response = await client.CreateTaskCollectionAsync("<jobId>", taskCollection);

This sample shows how to call CreateTaskCollectionAsync with all parameters.

Uri endpoint = new Uri("<https://my-service.azure.com>");
TokenCredential credential = new DefaultAzureCredential();
BatchClient client = new BatchClient(endpoint, credential);

BatchTaskGroup taskCollection = new BatchTaskGroup(new BatchTaskCreateContent[]
{
    new BatchTaskCreateContent("<id>", "<commandLine>")
    {
        DisplayName = "<displayName>",
        ExitConditions = new ExitConditions
        {
            ExitCodes = {new ExitCodeMapping(1234, new ExitOptions
            {
                JobAction = BatchJobAction.None,
                DependencyAction = DependencyAction.Satisfy,
            })},
            ExitCodeRanges = {new ExitCodeRangeMapping(1234, 1234, default)},
            PreProcessingError = default,
            FileUploadError = default,
            Default = default,
        },
        ContainerSettings = new BatchTaskContainerSettings("<imageName>")
        {
            ContainerRunOptions = "<containerRunOptions>",
            Registry = new ContainerRegistryReference
            {
                Username = "<username>",
                Password = "<password>",
                RegistryServer = "<registryServer>",
                IdentityReference = new BatchNodeIdentityReference
                {
                    ResourceId = "<resourceId>",
                },
            },
            WorkingDirectory = ContainerWorkingDirectory.TaskWorkingDirectory,
        },
        ResourceFiles = {new ResourceFile
        {
            AutoStorageContainerName = "<autoStorageContainerName>",
            StorageContainerUrl = "<storageContainerUrl>",
            HttpUrl = "<httpUrl>",
            BlobPrefix = "<blobPrefix>",
            FilePath = "<filePath>",
            FileMode = "<fileMode>",
            IdentityReference = default,
        }},
        OutputFiles = {new OutputFile("<filePattern>", new OutputFileDestination
        {
            Container = new OutputFileBlobContainerDestination("<containerUrl>")
            {
                Path = "<path>",
                IdentityReference = default,
                UploadHeaders = {new HttpHeader("<name>")
                {
                    Value = "<value>",
                }},
            },
        }, new OutputFileUploadConfig(OutputFileUploadCondition.TaskSuccess))},
        EnvironmentSettings = {new EnvironmentSetting("<name>")
        {
            Value = "<value>",
        }},
        AffinityInfo = new AffinityInfo("<affinityId>"),
        Constraints = new BatchTaskConstraints
        {
            MaxWallClockTime = XmlConvert.ToTimeSpan("PT1H23M45S"),
            RetentionTime = XmlConvert.ToTimeSpan("PT1H23M45S"),
            MaxTaskRetryCount = 1234,
        },
        RequiredSlots = 1234,
        UserIdentity = new UserIdentity
        {
            Username = "<username>",
            AutoUser = new AutoUserSpecification
            {
                Scope = AutoUserScope.Task,
                ElevationLevel = ElevationLevel.NonAdmin,
            },
        },
        MultiInstanceSettings = new MultiInstanceSettings("<coordinationCommandLine>")
        {
            NumberOfInstances = 1234,
            CommonResourceFiles = {default},
        },
        DependsOn = new BatchTaskDependencies
        {
            TaskIds = {"<taskIds>"},
            TaskIdRanges = {new BatchTaskIdRange(1234, 1234)},
        },
        ApplicationPackageReferences = {new BatchApplicationPackageReference("<applicationId>")
        {
            Version = "<version>",
        }},
        AuthenticationTokenSettings = new AuthenticationTokenSettings
        {
            Access = {AccessScope.Job},
        },
    }
});
Response<BatchTaskAddCollectionResult> response = await client.CreateTaskCollectionAsync("<jobId>", taskCollection, timeOutInSeconds: 1234, ocpdate: DateTimeOffset.Parse("Tue, 10 May 2022 18:57:31 GMT"));

Remarks

Note that each Task must have a unique ID. The Batch service may not return the results for each Task in the same order the Tasks were submitted in this request. If the server times out or the connection is closed during the request, the request may have been partially or fully processed, or not at all. In such cases, the user should re-issue the request. Note that it is up to the user to correctly handle failures when re-issuing a request. For example, you should use the same Task IDs during a retry so that if the prior operation succeeded, the retry will not create extra Tasks unexpectedly. If the response contains any Tasks which failed to add, a client can retry the request. In a retry, it is most efficient to resubmit only Tasks that failed to add, and to omit Tasks that were successfully added on the first attempt. The maximum lifetime of a Task from addition to completion is 180 days. If a Task has not completed within 180 days of being added it will be terminated by the Batch service and left in whatever state it was in at that time.

Applies to

CreateTaskCollectionAsync(String, RequestContent, Nullable<Int32>, Nullable<DateTimeOffset>, RequestContext)

[Protocol Method] Adds a collection of Tasks to the specified Job.

public virtual System.Threading.Tasks.Task<Azure.Response> CreateTaskCollectionAsync (string jobId, Azure.Core.RequestContent content, int? timeOutInSeconds = default, DateTimeOffset? ocpdate = default, Azure.RequestContext context = default);
abstract member CreateTaskCollectionAsync : string * Azure.Core.RequestContent * Nullable<int> * Nullable<DateTimeOffset> * Azure.RequestContext -> System.Threading.Tasks.Task<Azure.Response>
override this.CreateTaskCollectionAsync : string * Azure.Core.RequestContent * Nullable<int> * Nullable<DateTimeOffset> * Azure.RequestContext -> System.Threading.Tasks.Task<Azure.Response>
Public Overridable Function CreateTaskCollectionAsync (jobId As String, content As RequestContent, Optional timeOutInSeconds As Nullable(Of Integer) = Nothing, Optional ocpdate As Nullable(Of DateTimeOffset) = Nothing, Optional context As RequestContext = Nothing) As Task(Of Response)

Parameters

jobId
String

The ID of the Job to which the Task collection is to be added.

content
RequestContent

The content to send as the body of the request.

timeOutInSeconds
Nullable<Int32>

The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.".

ocpdate
Nullable<DateTimeOffset>

The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly.

context
RequestContext

The request context, which can override default behaviors of the client pipeline on a per-call basis.

Returns

The response returned from the service.

Exceptions

jobId or content is null.

jobId is an empty string, and was expected to be non-empty.

Service returned a non-success status code.

Examples

This sample shows how to call CreateTaskCollectionAsync and parse the result.

Uri endpoint = new Uri("<https://my-service.azure.com>");
TokenCredential credential = new DefaultAzureCredential();
BatchClient client = new BatchClient(endpoint, credential);

using RequestContent content = RequestContent.Create(new
{
    value = new object[]
    {
        new
        {
            id = "<id>",
            commandLine = "<commandLine>",
        }
    },
});
Response response = await client.CreateTaskCollectionAsync("<jobId>", content);

JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement;
Console.WriteLine(result.ToString());

This sample shows how to call CreateTaskCollectionAsync with all parameters and request content and parse the result.

Uri endpoint = new Uri("<https://my-service.azure.com>");
TokenCredential credential = new DefaultAzureCredential();
BatchClient client = new BatchClient(endpoint, credential);

using RequestContent content = RequestContent.Create(new
{
    value = new object[]
    {
        new
        {
            id = "<id>",
            displayName = "<displayName>",
            exitConditions = new Dictionary<string, object>
            {
                ["exitCodes"] = new object[]
                {
                    new
                    {
                        code = 1234,
                        exitOptions = new
                        {
                            jobAction = "none",
                            dependencyAction = "satisfy",
                        },
                    }
                },
                ["exitCodeRanges"] = new object[]
                {
                    new
                    {
                        start = 1234,
                        end = 1234,
                    }
                },
                ["preProcessingError"] = null,
                ["fileUploadError"] = null,
                ["default"] = null
            },
            commandLine = "<commandLine>",
            containerSettings = new
            {
                containerRunOptions = "<containerRunOptions>",
                imageName = "<imageName>",
                registry = new
                {
                    username = "<username>",
                    password = "<password>",
                    registryServer = "<registryServer>",
                    identityReference = new
                    {
                        resourceId = "<resourceId>",
                    },
                },
                workingDirectory = "taskWorkingDirectory",
            },
            resourceFiles = new object[]
            {
                new
                {
                    autoStorageContainerName = "<autoStorageContainerName>",
                    storageContainerUrl = "<storageContainerUrl>",
                    httpUrl = "<httpUrl>",
                    blobPrefix = "<blobPrefix>",
                    filePath = "<filePath>",
                    fileMode = "<fileMode>",
                }
            },
            outputFiles = new object[]
            {
                new
                {
                    filePattern = "<filePattern>",
                    destination = new
                    {
                        container = new
                        {
                            path = "<path>",
                            containerUrl = "<containerUrl>",
                            uploadHeaders = new object[]
                            {
                                new
                                {
                                    name = "<name>",
                                    value = "<value>",
                                }
                            },
                        },
                    },
                    uploadOptions = new
                    {
                        uploadCondition = "tasksuccess",
                    },
                }
            },
            environmentSettings = new object[]
            {
                new
                {
                    name = "<name>",
                    value = "<value>",
                }
            },
            affinityInfo = new
            {
                affinityId = "<affinityId>",
            },
            constraints = new
            {
                maxWallClockTime = "PT1H23M45S",
                retentionTime = "PT1H23M45S",
                maxTaskRetryCount = 1234,
            },
            requiredSlots = 1234,
            userIdentity = new
            {
                username = "<username>",
                autoUser = new
                {
                    scope = "task",
                    elevationLevel = "nonadmin",
                },
            },
            multiInstanceSettings = new
            {
                numberOfInstances = 1234,
                coordinationCommandLine = "<coordinationCommandLine>",
                commonResourceFiles = new object[]
                {
                    null
                },
            },
            dependsOn = new
            {
                taskIds = new object[]
                {
                    "<taskIds>"
                },
                taskIdRanges = new object[]
                {
                    new
                    {
                        start = 1234,
                        end = 1234,
                    }
                },
            },
            applicationPackageReferences = new object[]
            {
                new
                {
                    applicationId = "<applicationId>",
                    version = "<version>",
                }
            },
            authenticationTokenSettings = new
            {
                access = new object[]
                {
                    "job"
                },
            },
        }
    },
});
Response response = await client.CreateTaskCollectionAsync("<jobId>", content, timeOutInSeconds: 1234, ocpdate: DateTimeOffset.Parse("Tue, 10 May 2022 18:57:31 GMT"));

JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement;
Console.WriteLine(result.GetProperty("value")[0].GetProperty("status").ToString());
Console.WriteLine(result.GetProperty("value")[0].GetProperty("taskId").ToString());
Console.WriteLine(result.GetProperty("value")[0].GetProperty("eTag").ToString());
Console.WriteLine(result.GetProperty("value")[0].GetProperty("lastModified").ToString());
Console.WriteLine(result.GetProperty("value")[0].GetProperty("location").ToString());
Console.WriteLine(result.GetProperty("value")[0].GetProperty("error").GetProperty("code").ToString());
Console.WriteLine(result.GetProperty("value")[0].GetProperty("error").GetProperty("message").GetProperty("lang").ToString());
Console.WriteLine(result.GetProperty("value")[0].GetProperty("error").GetProperty("message").GetProperty("value").ToString());
Console.WriteLine(result.GetProperty("value")[0].GetProperty("error").GetProperty("values")[0].GetProperty("key").ToString());
Console.WriteLine(result.GetProperty("value")[0].GetProperty("error").GetProperty("values")[0].GetProperty("value").ToString());

Applies to