Skip to content

Instantly share code, notes, and snippets.

@veyodev
Created August 22, 2017 19:53
Show Gist options
  • Save veyodev/1ced0db08110c69b05ea9b242c486328 to your computer and use it in GitHub Desktop.
Save veyodev/1ced0db08110c69b05ea9b242c486328 to your computer and use it in GitHub Desktop.
async Task Main()
{
// Name of the tool.
const string toolName = "ImportTool";
// Simulate a job that runs for 2 minutes.
var job = new Task(() => {
Thread.Sleep(TimeSpan.FromMinutes(2));
});
// Prevent multiple instances of this job from running at the same time.
var mutex = new DistributedMutex(ConfigurationManager.AppSettings["StorageConnectionString"],
ConfigurationManager.AppSettings["StorageContainerName"],
toolName);
// Obtain lock before job starts.
// This will throw exceptions if another job is running.
await mutex.AcquireAsync();
// Start the job now.
job.Start();
Console.WriteLine($"{toolName} is running...");
// Renew the lease every 55 seconds before it expires at 60 seconds.
var timer = new System.Timers.Timer(55000);
timer.Elapsed += async (sender, e) => {
try {
// Has the job finished?
// Finished means one of three final states: RanToCompletion, Faulted, or Canceled.
if (job.IsCompleted) {
// Try to release lock silently.
try {
await mutex.ReleaseAsync();
}
catch {}
timer.Dispose();
}
else {
// Renew the lease.
await mutex.RenewAsync();
}
}
catch (Exception ex) {
//logger.Error(ex, $"Error while renewing the lease for account {key}.");
Console.WriteLine(ex.Message);
}
};
// Start timer.
timer.Start();
// Wait for job to finish.
await job.ConfigureAwait(false);
Console.WriteLine($"{toolName} job finished.");
// Release lock immediately so another instance can get launched.
try {
await mutex.ReleaseAsync();
}
catch {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment