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 TIMED_OUT. The host process will be terminated immediately.

Java
package stkscalabilitysdk.howto;


import agi.parallel.client.ClusterJobScheduler;
import agi.parallel.client.IJobScheduler;
import agi.parallel.client.Job;
import agi.parallel.infrastructure.Task;

public class SpecifyHowLongTaskRuns {
    public static void main(String[] args) {
        IJobScheduler scheduler = new ClusterJobScheduler("localhost");
        try {
            scheduler.connect();
            Job job = scheduler.createJob();

            // For example, specify to let the tasks run for 20 seconds.
            job.setTaskExecutionTimeout(20000);

            Task task = new LongRunningTask();
            job.addTask(task);
            job.submit();
            job.waitUntilDone();

            System.out.println("TaskStatus = " + task.getTaskStatus());
        } finally {
            scheduler.dispose();
        }

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

    private static class LongRunningTask extends Task {
        @Override
        public void execute() {
            // For example, sleep forever. If TaskExecutionTimeout was not specified, this task would run forever.
            try {
                Thread.sleep(Long.MAX_VALUE);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
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

Other Resources

STK Scalability 1.4 API for Java