Submit a job for execution and wait for completion
This example demonstrates how to submit a job for execution and then wait until execution has completed.
The Execute method returns a collection of all the instances created for the execution request (there may be more than one instance if the job runs in a queue that targets multiple agents). To wait for completion, you must periodically refresh the status of each of these instances until all have finished running.
void RunJobAndWait(Job job)
{
var options = new JobExecutionSettings();
//submit the job
var result = job.Execute(options);
if (!result.JobSubmitted)
{
//The job could not be submitted. The result.Messages collection will contain the error message(s)
return;
}
var waitingInstances = new List<ExecutionHistoryItem>();
//result.Instances has all the instances created for this request
//make a new collection of them
waitingInstances.AddRange(result.Instances);
while (waitingInstances.Any())
{
//Sleep for some reasonable period before checking again
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(30));
//look at each instance that we're still waiting on
foreach (var instance in waitingInstances.ToArray())
{
//Refresh the instance to get its latest status from the server
instance.Refresh();
//The instance is created with state NotRun. If we poll the server before the execution process has gotten
//underway it's possible the instance will still have that state, so we treat that the same as if it were running.
//The IsRunning property returns true if the job is in any of the active job states
if (instance.Status != JobState.NotRun && !instance.IsRunning)
{
//if the instance is no longer running, remove it from the list of instances we're waiting on.
waitingInstances.Remove(instance);
}
}
//if all instances have completed, waitingInstances will be empty and we're finished
}
}