Cancel job and all its child tasks |
You want to cancel a job.
There are two ways to cancel tasks on a job.
Method 1: Set the JobCancelOnTaskFailure property to true to cancel a job's tasks automatically if one of the tasks fails. Use this option if the result of a job depends on all its child tasks completing successfully.
using System; using System.Threading; using AGI.Parallel.Client; using AGI.Parallel.Infrastructure; namespace CodeSamples { class Program { static void Main(string[] args) { using (IJobScheduler scheduler = new ClusterJobScheduler("localhost")) { scheduler.Connect(); Job job = scheduler.CreateJob(); job.CancelOnTaskFailure = true; for (int i = 0; i < 3; ++i) { job.AddTask(new WaitTask()); } // This task will fail. Watch as the other tasks are canceled. job.AddTask(new FailureTask()); job.Submit(); job.WaitUntilDone(); for (int i = 0; i < 4; ++i) { Console.WriteLine("Task #{0} Status {1}", i + 1, job.Tasks[i].TaskStatus); } } /* * The output of the application should resemble: * Task #1 Status Canceled * Task #2 Status Canceled * Task #3 Status Canceled * Task #4 Status Failed */ } [Serializable] class WaitTask : Task { public override void Execute() { for (int i = 0; i < 100; ++i) { Thread.Sleep(100); } } } [Serializable] class FailureTask : Task { public override void Execute() { Thread.Sleep(100); throw new Exception("Failure"); } } } }
Method 2: The other option is to explicitly cancel the job using the Cancel method.
Tip |
---|
By default, the client will not wait until the task is fully canceled. To wait for the job to complete, use the overload to Cancel and pass true to the listenForCancellationEvent parameter. |
using System; using System.Threading; using AGI.Parallel.Client; using AGI.Parallel.Infrastructure; namespace CodeSamples { class Program { static void Main(string[] args) { using (IJobScheduler scheduler = new ClusterJobScheduler("localhost")) { scheduler.Connect(); Job job = scheduler.CreateJob(); for (int i = 0; i < 100; ++i) { job.AddTask(new WaitTask()); } job.Submit(); // Wait 10 seconds so the tasks queue up. Thread.Sleep(10000); // Cancel all the tasks in this job. job.Cancel(); job.WaitUntilDone(); } } [Serializable] class WaitTask : Task { public override void Execute() { for (int i = 0; i < 100; ++i) { Thread.Sleep(100); } } } } }
Within a task, check the TaskIsCancelling flag. If IsCancelling is true, try to exit out of the task as soon as possible. Each task is given 30 seconds to gracefully finish before the process is terminated. This value can be configured by setting TaskPropertiesGracefulCancellationTimeOut.
STK Parallel Computing Server 2.9 API for .NET