Click or drag to resize

Specify the maximum amount of time a task should run

Problem

You want to limit how long a task runs.

Solution

Set the TaskExecutionTimeout option on the job to the maximum amount of time for which a task should run. The value is expected to be in milliseconds.

If a task runs longer than the time specified, the task will be canceled and its task status will be TimedOut. The host process will be terminated immediately.

C#
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 example, specify to let the tasks run for 20 seconds.
                job.TaskExecutionTimeout = 20000;

                Task task = new LongRunningTask();
                job.AddTask(task);
                job.Submit();
                job.WaitUntilDone();

                Console.WriteLine("TaskStatus = {0}", task.TaskStatus);
           }

           /*
            * The output of the application should resemble:
            * TaskStatus = TimedOut.
            */
        }

        [Serializable]
        class LongRunningTask : Task
        {
            public override void Execute()
            {
                // For example, sleep forever. If TaskExecutionTimeout was not specified, this task would run forever.
                Thread.Sleep(Timeout.Infinite);
            }
        }
    }
}
Discussion

By default a task can run indefinitely until it completes or is canceled. This behavior can be changed for scenarios where the task can run for a variable amount of time and a hard limit on the maximum time it can run is needed. This problem arises often when working with unpredictable data sets.

See Also

STK Parallel Computing Server 2.9 API for .NET