Skip to content

Commit

Permalink
Some cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
niemyjski committed Jul 19, 2024
1 parent d146638 commit b4c6781
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 47 deletions.
78 changes: 38 additions & 40 deletions src/Foundatio/Jobs/IJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,56 +36,54 @@ public static async Task RunContinuousAsync(this IJob job, TimeSpan? interval =
string jobName = job.GetType().Name;
var logger = job.GetLogger();

using (logger.BeginScope(new Dictionary<string, object> { { "job", jobName } }))
using var _ = logger.BeginScope(new Dictionary<string, object> { { "job", jobName } });
if (logger.IsEnabled(LogLevel.Information))
logger.LogInformation("Starting continuous job type {JobName} on machine {MachineName}...", jobName, Environment.MachineName);

while (!cancellationToken.IsCancellationRequested)
{
if (logger.IsEnabled(LogLevel.Information))
logger.LogInformation("Starting continuous job type {JobName} on machine {MachineName}...", jobName, Environment.MachineName);
var result = await job.TryRunAsync(cancellationToken).AnyContext();
logger.LogJobResult(result, jobName);
iterations++;

if (cancellationToken.IsCancellationRequested || (iterationLimit > -1 && iterationLimit <= iterations))
break;

while (!cancellationToken.IsCancellationRequested)
if (result.Error != null)
{
await SystemClock.SleepSafeAsync(Math.Max((int)(interval?.TotalMilliseconds ?? 0), 100), cancellationToken).AnyContext();
}
else if (interval.HasValue && interval.Value > TimeSpan.Zero)
{
var result = await job.TryRunAsync(cancellationToken).AnyContext();
logger.LogJobResult(result, jobName);
iterations++;
await SystemClock.SleepSafeAsync(interval.Value, cancellationToken).AnyContext();
}

if (cancellationToken.IsCancellationRequested || (iterationLimit > -1 && iterationLimit <= iterations))
break;
// needed to yield back a task for jobs that aren't async
await Task.Yield();

if (result.Error != null)
{
await SystemClock.SleepSafeAsync(Math.Max((int)(interval?.TotalMilliseconds ?? 0), 100), cancellationToken).AnyContext();
}
else if (interval.HasValue && interval.Value > TimeSpan.Zero)
{
await SystemClock.SleepSafeAsync(interval.Value, cancellationToken).AnyContext();
}
if (cancellationToken.IsCancellationRequested)
break;

// needed to yield back a task for jobs that aren't async
await Task.Yield();
if (continuationCallback == null)
continue;

if (cancellationToken.IsCancellationRequested)
try
{
if (!await continuationCallback().AnyContext())
break;

if (continuationCallback == null)
continue;

try
{
if (!await continuationCallback().AnyContext())
break;
}
catch (Exception ex)
{
if (logger.IsEnabled(LogLevel.Error))
logger.LogError(ex, "Error in continuation callback: {Message}", ex.Message);
}
}
catch (Exception ex)
{
if (logger.IsEnabled(LogLevel.Error))
logger.LogError(ex, "Error in continuation callback: {Message}", ex.Message);
}
}

logger.LogInformation("Finished continuous job type {JobName}: {IterationLimit} {Iterations}", jobName, Environment.MachineName, iterationLimit, iterations);
if (cancellationToken.IsCancellationRequested && logger.IsEnabled(LogLevel.Trace))
logger.LogTrace("Job cancellation requested");
logger.LogInformation("Finished continuous job type {JobName}: {IterationLimit} {Iterations}", jobName, Environment.MachineName, iterationLimit, iterations);
if (cancellationToken.IsCancellationRequested && logger.IsEnabled(LogLevel.Trace))
logger.LogTrace("Job cancellation requested");

if (logger.IsEnabled(LogLevel.Information))
logger.LogInformation("Stopping continuous job type {JobName} on machine {MachineName}...", jobName, Environment.MachineName);
}
if (logger.IsEnabled(LogLevel.Information))
logger.LogInformation("Stopping continuous job type {JobName} on machine {MachineName}...", jobName, Environment.MachineName);
}
}
4 changes: 2 additions & 2 deletions src/Foundatio/Jobs/JobResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public static void LogJobResult(this ILogger logger, JobResult result, string jo
if (result == null)
{
if (logger.IsEnabled(LogLevel.Error))
logger.LogError("Null job run result for {JobName}.", jobName);
logger.LogError("Null job run result for {JobName}", jobName);

return;
}
Expand All @@ -83,6 +83,6 @@ public static void LogJobResult(this ILogger logger, JobResult result, string jo
else if (!String.IsNullOrEmpty(result.Message))
logger.LogInformation("Job run {JobName} succeeded: {Message}", jobName, result.Message);
else if (logger.IsEnabled(LogLevel.Debug))
logger.LogDebug("Job run {JobName} succeeded.", jobName);
logger.LogDebug("Job run {JobName} succeeded", jobName);
}
}
2 changes: 1 addition & 1 deletion src/Foundatio/Lock/ILockProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ public static async Task<ILock> AcquireAsync(this ILockProvider provider, IEnume
break;
}

// Renew any acquired locks so they stay alive until we have all locks
// Renew any acquired locks, so they stay alive until we have all locks
if (acquiredLocks.Count > 0 && renewTime > TimeSpan.Zero)
{
var utcNow = SystemClock.UtcNow;
Expand Down
4 changes: 2 additions & 2 deletions src/Foundatio/Queues/QueueBase.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
Expand Down Expand Up @@ -354,7 +354,7 @@ public override void Dispose()
{
if (_isDisposed)
{
_logger.LogTrace("Queue {Name} ({Id}) dispose was already called.", _options.Name, QueueId);
_logger.LogTrace("Queue {Name} ({Id}) dispose was already called", _options.Name, QueueId);
return;
}

Expand Down
4 changes: 2 additions & 2 deletions tests/Foundatio.Tests/Queue/InMemoryQueueTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -384,11 +384,11 @@ public InMemoryQueue_Issue239(ILoggerFactory loggerFactory)
// https://github.com/FoundatioFx/Foundatio/issues/239
public virtual async Task CompleteOnAutoAbandonedHandledProperly_Issue239()
{
// create queue with short work item timeout so it will be auto abandoned
// create queue with short work item timeout, so it will be auto abandoned
var queue = new InMemoryQueue_Issue239<SimpleWorkItem>(Log);
using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30));

// completion source to wait for CompleteAsync call before the assert
// completion source to wait for CompleteAsync call before to assert
var taskCompletionSource = new TaskCompletionSource<bool>();

// start handling items
Expand Down

0 comments on commit b4c6781

Please sign in to comment.