Skip to content

Instantly share code, notes, and snippets.

@srkirkland
Created February 8, 2013 22:49
Show Gist options
  • Save srkirkland/4742595 to your computer and use it in GitHub Desktop.
Save srkirkland/4742595 to your computer and use it in GitHub Desktop.
waiting for existing jobs to exit when worker role is stopped
public override void OnStop()
{
_roleLogger.Info("Worker Role Exiting");
_host.Stop();
var scheduler = StdSchedulerFactory.GetDefaultScheduler();
var executingJobs = scheduler.GetCurrentlyExecutingJobs();
if (executingJobs.Count > 0)
{
//If we have any currently executing jobs, pause new ones from being triggered and wait for them to finish
_roleLogger.InfoFormat("Waiting for {0} jobs to shut down before exiting", executingJobs.Count);
scheduler.PauseAll();
TimeSpan loopDuration = TimeSpan.FromSeconds(20); //check for running jobs every 20 seconds
for (TimeSpan time = TimeSpan.FromSeconds(0); time < MaxExitWaitTime; time += loopDuration)
{
if (scheduler.GetCurrentlyExecutingJobs().Count == 0)
{
break;
}
Thread.Sleep(loopDuration);
}
executingJobs = scheduler.GetCurrentlyExecutingJobs();
if (executingJobs.Count > 0) //if there are still executing jobs that still haven't finished Azure will shut them down hard
{
foreach (var job in executingJobs)
{
var jobLogger = LogManager.GetLogger(job.JobDetail.JobType);
jobLogger.Error("Job hard shutdown forced by worker role restart");
}
}
}
base.OnStop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment