|
Add this skill
npx mdskills install sickn33/azure-compute-batch-javaComprehensive SDK reference with detailed examples across all major operations
1---2name: azure-compute-batch-java3description: |4 Azure Batch SDK for Java. Run large-scale parallel and HPC batch jobs with pools, jobs, tasks, and compute nodes.5 Triggers: "BatchClient java", "azure batch java", "batch pool java", "batch job java", "HPC java", "parallel computing java".6---78# Azure Batch SDK for Java910Client library for running large-scale parallel and high-performance computing (HPC) batch jobs in Azure.1112## Installation1314```xml15<dependency>16 <groupId>com.azure</groupId>17 <artifactId>azure-compute-batch</artifactId>18 <version>1.0.0-beta.5</version>19</dependency>20```2122## Prerequisites2324- Azure Batch account25- Pool configured with compute nodes26- Azure subscription2728## Environment Variables2930```bash31AZURE_BATCH_ENDPOINT=https://<account>.<region>.batch.azure.com32AZURE_BATCH_ACCOUNT=<account-name>33AZURE_BATCH_ACCESS_KEY=<account-key>34```3536## Client Creation3738### With Microsoft Entra ID (Recommended)3940```java41import com.azure.compute.batch.BatchClient;42import com.azure.compute.batch.BatchClientBuilder;43import com.azure.identity.DefaultAzureCredentialBuilder;4445BatchClient batchClient = new BatchClientBuilder()46 .credential(new DefaultAzureCredentialBuilder().build())47 .endpoint(System.getenv("AZURE_BATCH_ENDPOINT"))48 .buildClient();49```5051### Async Client5253```java54import com.azure.compute.batch.BatchAsyncClient;5556BatchAsyncClient batchAsyncClient = new BatchClientBuilder()57 .credential(new DefaultAzureCredentialBuilder().build())58 .endpoint(System.getenv("AZURE_BATCH_ENDPOINT"))59 .buildAsyncClient();60```6162### With Shared Key Credentials6364```java65import com.azure.core.credential.AzureNamedKeyCredential;6667String accountName = System.getenv("AZURE_BATCH_ACCOUNT");68String accountKey = System.getenv("AZURE_BATCH_ACCESS_KEY");69AzureNamedKeyCredential sharedKeyCreds = new AzureNamedKeyCredential(accountName, accountKey);7071BatchClient batchClient = new BatchClientBuilder()72 .credential(sharedKeyCreds)73 .endpoint(System.getenv("AZURE_BATCH_ENDPOINT"))74 .buildClient();75```7677## Key Concepts7879| Concept | Description |80|---------|-------------|81| Pool | Collection of compute nodes that run tasks |82| Job | Logical grouping of tasks |83| Task | Unit of computation (command/script) |84| Node | VM that executes tasks |85| Job Schedule | Recurring job creation |8687## Pool Operations8889### Create Pool9091```java92import com.azure.compute.batch.models.*;9394batchClient.createPool(new BatchPoolCreateParameters("myPoolId", "STANDARD_DC2s_V2")95 .setVirtualMachineConfiguration(96 new VirtualMachineConfiguration(97 new BatchVmImageReference()98 .setPublisher("Canonical")99 .setOffer("UbuntuServer")100 .setSku("22_04-lts")101 .setVersion("latest"),102 "batch.node.ubuntu 22.04"))103 .setTargetDedicatedNodes(2)104 .setTargetLowPriorityNodes(0), null);105```106107### Get Pool108109```java110BatchPool pool = batchClient.getPool("myPoolId");111System.out.println("Pool state: " + pool.getState());112System.out.println("Current dedicated nodes: " + pool.getCurrentDedicatedNodes());113```114115### List Pools116117```java118import com.azure.core.http.rest.PagedIterable;119120PagedIterable<BatchPool> pools = batchClient.listPools();121for (BatchPool pool : pools) {122 System.out.println("Pool: " + pool.getId() + ", State: " + pool.getState());123}124```125126### Resize Pool127128```java129import com.azure.core.util.polling.SyncPoller;130131BatchPoolResizeParameters resizeParams = new BatchPoolResizeParameters()132 .setTargetDedicatedNodes(4)133 .setTargetLowPriorityNodes(2);134135SyncPoller<BatchPool, BatchPool> poller = batchClient.beginResizePool("myPoolId", resizeParams);136poller.waitForCompletion();137BatchPool resizedPool = poller.getFinalResult();138```139140### Enable AutoScale141142```java143BatchPoolEnableAutoScaleParameters autoScaleParams = new BatchPoolEnableAutoScaleParameters()144 .setAutoScaleEvaluationInterval(Duration.ofMinutes(5))145 .setAutoScaleFormula("$TargetDedicatedNodes = min(10, $PendingTasks.GetSample(TimeInterval_Minute * 5));");146147batchClient.enablePoolAutoScale("myPoolId", autoScaleParams);148```149150### Delete Pool151152```java153SyncPoller<BatchPool, Void> deletePoller = batchClient.beginDeletePool("myPoolId");154deletePoller.waitForCompletion();155```156157## Job Operations158159### Create Job160161```java162batchClient.createJob(163 new BatchJobCreateParameters("myJobId", new BatchPoolInfo().setPoolId("myPoolId"))164 .setPriority(100)165 .setConstraints(new BatchJobConstraints()166 .setMaxWallClockTime(Duration.ofHours(24))167 .setMaxTaskRetryCount(3)),168 null);169```170171### Get Job172173```java174BatchJob job = batchClient.getJob("myJobId", null, null);175System.out.println("Job state: " + job.getState());176```177178### List Jobs179180```java181PagedIterable<BatchJob> jobs = batchClient.listJobs(new BatchJobsListOptions());182for (BatchJob job : jobs) {183 System.out.println("Job: " + job.getId() + ", State: " + job.getState());184}185```186187### Get Task Counts188189```java190BatchTaskCountsResult counts = batchClient.getJobTaskCounts("myJobId");191System.out.println("Active: " + counts.getTaskCounts().getActive());192System.out.println("Running: " + counts.getTaskCounts().getRunning());193System.out.println("Completed: " + counts.getTaskCounts().getCompleted());194```195196### Terminate Job197198```java199BatchJobTerminateParameters terminateParams = new BatchJobTerminateParameters()200 .setTerminationReason("Manual termination");201BatchJobTerminateOptions options = new BatchJobTerminateOptions().setParameters(terminateParams);202203SyncPoller<BatchJob, BatchJob> poller = batchClient.beginTerminateJob("myJobId", options, null);204poller.waitForCompletion();205```206207### Delete Job208209```java210SyncPoller<BatchJob, Void> deletePoller = batchClient.beginDeleteJob("myJobId");211deletePoller.waitForCompletion();212```213214## Task Operations215216### Create Single Task217218```java219BatchTaskCreateParameters task = new BatchTaskCreateParameters("task1", "echo 'Hello World'");220batchClient.createTask("myJobId", task);221```222223### Create Task with Exit Conditions224225```java226batchClient.createTask("myJobId", new BatchTaskCreateParameters("task2", "cmd /c exit 3")227 .setExitConditions(new ExitConditions()228 .setExitCodeRanges(Arrays.asList(229 new ExitCodeRangeMapping(2, 4,230 new ExitOptions().setJobAction(BatchJobActionKind.TERMINATE)))))231 .setUserIdentity(new UserIdentity()232 .setAutoUser(new AutoUserSpecification()233 .setScope(AutoUserScope.TASK)234 .setElevationLevel(ElevationLevel.NON_ADMIN))),235 null);236```237238### Create Task Collection (up to 100)239240```java241List<BatchTaskCreateParameters> taskList = Arrays.asList(242 new BatchTaskCreateParameters("task1", "echo Task 1"),243 new BatchTaskCreateParameters("task2", "echo Task 2"),244 new BatchTaskCreateParameters("task3", "echo Task 3")245);246BatchTaskGroup taskGroup = new BatchTaskGroup(taskList);247BatchCreateTaskCollectionResult result = batchClient.createTaskCollection("myJobId", taskGroup);248```249250### Create Many Tasks (no limit)251252```java253List<BatchTaskCreateParameters> tasks = new ArrayList<>();254for (int i = 0; i < 1000; i++) {255 tasks.add(new BatchTaskCreateParameters("task" + i, "echo Task " + i));256}257batchClient.createTasks("myJobId", tasks);258```259260### Get Task261262```java263BatchTask task = batchClient.getTask("myJobId", "task1");264System.out.println("Task state: " + task.getState());265System.out.println("Exit code: " + task.getExecutionInfo().getExitCode());266```267268### List Tasks269270```java271PagedIterable<BatchTask> tasks = batchClient.listTasks("myJobId");272for (BatchTask task : tasks) {273 System.out.println("Task: " + task.getId() + ", State: " + task.getState());274}275```276277### Get Task Output278279```java280import com.azure.core.util.BinaryData;281import java.nio.charset.StandardCharsets;282283BinaryData stdout = batchClient.getTaskFile("myJobId", "task1", "stdout.txt");284System.out.println(new String(stdout.toBytes(), StandardCharsets.UTF_8));285```286287### Terminate Task288289```java290batchClient.terminateTask("myJobId", "task1", null, null);291```292293## Node Operations294295### List Nodes296297```java298PagedIterable<BatchNode> nodes = batchClient.listNodes("myPoolId", new BatchNodesListOptions());299for (BatchNode node : nodes) {300 System.out.println("Node: " + node.getId() + ", State: " + node.getState());301}302```303304### Reboot Node305306```java307SyncPoller<BatchNode, BatchNode> rebootPoller = batchClient.beginRebootNode("myPoolId", "nodeId");308rebootPoller.waitForCompletion();309```310311### Get Remote Login Settings312313```java314BatchNodeRemoteLoginSettings settings = batchClient.getNodeRemoteLoginSettings("myPoolId", "nodeId");315System.out.println("IP: " + settings.getRemoteLoginIpAddress());316System.out.println("Port: " + settings.getRemoteLoginPort());317```318319## Job Schedule Operations320321### Create Job Schedule322323```java324batchClient.createJobSchedule(new BatchJobScheduleCreateParameters("myScheduleId",325 new BatchJobScheduleConfiguration()326 .setRecurrenceInterval(Duration.ofHours(6))327 .setDoNotRunUntil(OffsetDateTime.now().plusDays(1)),328 new BatchJobSpecification(new BatchPoolInfo().setPoolId("myPoolId"))329 .setPriority(50)),330 null);331```332333### Get Job Schedule334335```java336BatchJobSchedule schedule = batchClient.getJobSchedule("myScheduleId");337System.out.println("Schedule state: " + schedule.getState());338```339340## Error Handling341342```java343import com.azure.compute.batch.models.BatchErrorException;344import com.azure.compute.batch.models.BatchError;345346try {347 batchClient.getPool("nonexistent-pool");348} catch (BatchErrorException e) {349 BatchError error = e.getValue();350 System.err.println("Error code: " + error.getCode());351 System.err.println("Message: " + error.getMessage().getValue());352353 if ("PoolNotFound".equals(error.getCode())) {354 System.err.println("The specified pool does not exist.");355 }356}357```358359## Best Practices3603611. **Use Entra ID** — Preferred over shared key for authentication3622. **Use management SDK for pools** — `azure-resourcemanager-batch` supports managed identities3633. **Batch task creation** — Use `createTaskCollection` or `createTasks` for multiple tasks3644. **Handle LRO properly** — Pool resize, delete operations are long-running3655. **Monitor task counts** — Use `getJobTaskCounts` to track progress3666. **Set constraints** — Configure `maxWallClockTime` and `maxTaskRetryCount`3677. **Use low-priority nodes** — Cost savings for fault-tolerant workloads3688. **Enable autoscale** — Dynamically adjust pool size based on workload369370## Reference Links371372| Resource | URL |373|----------|-----|374| Maven Package | https://central.sonatype.com/artifact/com.azure/azure-compute-batch |375| GitHub | https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/batch/azure-compute-batch |376| API Documentation | https://learn.microsoft.com/java/api/com.azure.compute.batch |377| Product Docs | https://learn.microsoft.com/azure/batch/ |378| REST API | https://learn.microsoft.com/rest/api/batchservice/ |379| Samples | https://github.com/azure/azure-batch-samples |380
Full transparency — inspect the skill content before installing.