Skip to content

Commit

Permalink
fix: Don't allow multiple runs
Browse files Browse the repository at this point in the history
  • Loading branch information
linkdotnet committed Mar 22, 2024
1 parent c2d817e commit c31bb92
Showing 1 changed file with 23 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ namespace LinkDotNet.Blog.Web.Features;

public sealed partial class TransformBlogPostRecordsService : IJob
{
private static readonly SemaphoreSlim Semaphore = new(1, 1);
private readonly IRepository<BlogPost> blogPostRepository;
private readonly IRepository<UserRecord> userRecordRepository;
private readonly IRepository<BlogPostRecord> blogPostRecordRepository;
Expand All @@ -31,9 +32,25 @@ public TransformBlogPostRecordsService(

public async Task RunAsync(JobExecutionContext context, CancellationToken token)
{
LogTransformStarted();
await TransformRecordsAsync();
LogTransformStopped();
// In the future version of NCronJob we don't need this here,
// but can configure it via the AddCronJob method or similar ways
var hasLock = await Semaphore.WaitAsync(0, token);
if (!hasLock)
{
LogSkippingRun();
return;
}

try
{
LogTransformStarted();
await TransformRecordsAsync();
LogTransformStopped();
}
finally
{
Semaphore.Release();
}
}

private static IEnumerable<BlogPostRecord> GetBlogPostRecords(
Expand Down Expand Up @@ -112,4 +129,7 @@ private async Task TransformRecordsAsync()

[LoggerMessage(Level = LogLevel.Information, Message = "Deleted records from UserRecord-Table")]
private partial void LogDeletedUserRecords();

[LoggerMessage(Level = LogLevel.Information, Message = "There is already a running job. Skipping this run.")]
private partial void LogSkippingRun();
}

0 comments on commit c31bb92

Please sign in to comment.