public async Task Execute(IJobExecutionContext context) { _logger.LogInformation("Scheduled job run at: {Timestamp}", DateTime.UtcNow); var jobDataMap = context.JobDetail.JobDataMap; var jobHandlerType = jobDataMap[JobDataKeys.JobHandlerType] as Type; var singleton = jobDataMap[JobDataKeys.Singleton] as bool? ?? false; if (singleton) { await _lockManager.ExclusiveRun(context.JobDetail.Key.ToString(), token => ExecuteInternal(context, jobHandlerType, token), context.CancellationToken); return; } // No lock is needed so execute at will. await ExecuteInternal(context, jobHandlerType); }
/// <summary> /// Uses a lease on a shared resource imposed by the <see cref="ILockManager"/> (i.e an Azure Storage blob or a shared file in a NFS) to provide a mechanism for implementing a shared, distributed mutex. /// </summary> /// <remarks> /// This mutex can be used to elect a leader among a group of role instances in an Azure cloud service or an on-premise infrastructure. /// The first role instance to acquire the lease is elected the leader, and remains the leader until it releases the lease or isn't able to renew the lease. /// </remarks> /// <param name="manager">The instance of <see cref="ILockManager"/>.</param> /// <param name="task">A task that references the code that the role instance should run if it successfully acquires the lease over the blob and is elected the leader.</param> /// <param name="taskName">A name for the task to run.</param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> /// <returns>The task that represents the asynchronous operation result for running the specified delegate.</returns> public static Task ExclusiveRun(this ILockManager manager, string taskName, Func <CancellationToken, Task> task, CancellationToken cancellationToken) => manager.ExclusiveRun(taskName, task, cancellationToken, ExclusiveRunOptions.Default());