Skip to content

Change background job notification timing #15201

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public class RecurringBackgroundJobHostedService<TJob> : RecurringHostedServiceB
private readonly IServerRoleAccessor _serverRoleAccessor;
private readonly IEventAggregator _eventAggregator;
private readonly IRecurringBackgroundJob _job;
private readonly string _jobName;

public RecurringBackgroundJobHostedService(
IRuntimeState runtimeState,
Expand All @@ -54,52 +55,56 @@ public RecurringBackgroundJobHostedService(
_serverRoleAccessor = serverRoleAccessor;
_eventAggregator = eventAggregator;
_job = job;
_jobName = job.GetType().Name;

_job.PeriodChanged += (sender, e) => ChangePeriod(_job.Period);
}

public string JobName { get { return _jobName; } }

/// <inheritdoc />
public override async Task PerformExecuteAsync(object? state)
{
var executingNotification = new Notifications.RecurringBackgroundJobExecutingNotification(_job, new EventMessages());
await _eventAggregator.PublishAsync(executingNotification);
_logger.LogDebug($"Job {_jobName} checking");

try
if (_runtimeState.Level != RuntimeLevel.Run)
{
_logger.LogDebug($"Job {_jobName} not running as runlevel not yet ready");
await _eventAggregator.PublishAsync(new Notifications.RecurringBackgroundJobIgnoredNotification(_job, new EventMessages()));
return;
}

// Don't run on replicas nor unknown role servers
if (!_job.ServerRoles.Contains(_serverRoleAccessor.CurrentServerRole))
{
_logger.LogDebug($"Job {_jobName} not running on this server role");
await _eventAggregator.PublishAsync(new Notifications.RecurringBackgroundJobIgnoredNotification(_job, new EventMessages()));
return;
}

// Ensure we do not run if not main domain, but do NOT lock it
if (!_mainDom.IsMainDom)
{
_logger.LogDebug($"Job {_jobName} not running as not MainDom");
await _eventAggregator.PublishAsync(new Notifications.RecurringBackgroundJobIgnoredNotification(_job, new EventMessages()));
return;
}

if (_runtimeState.Level != RuntimeLevel.Run)
{
_logger.LogDebug("Job not running as runlevel not yet ready");
await _eventAggregator.PublishAsync(new Notifications.RecurringBackgroundJobIgnoredNotification(_job, new EventMessages()).WithStateFrom(executingNotification));
return;
}

// Don't run on replicas nor unknown role servers
if (!_job.ServerRoles.Contains(_serverRoleAccessor.CurrentServerRole))
{
_logger.LogDebug("Job not running on this server role");
await _eventAggregator.PublishAsync(new Notifications.RecurringBackgroundJobIgnoredNotification(_job, new EventMessages()).WithStateFrom(executingNotification));
return;
}

// Ensure we do not run if not main domain, but do NOT lock it
if (!_mainDom.IsMainDom)
{
_logger.LogDebug("Job not running as not MainDom");
await _eventAggregator.PublishAsync(new Notifications.RecurringBackgroundJobIgnoredNotification(_job, new EventMessages()).WithStateFrom(executingNotification));
return;
}
var executingNotification = new Notifications.RecurringBackgroundJobExecutingNotification(_job, new EventMessages());

try
{

_logger.LogDebug($"Job {_jobName} executing");
await _job.RunJobAsync();
await _eventAggregator.PublishAsync(new Notifications.RecurringBackgroundJobExecutedNotification(_job, new EventMessages()).WithStateFrom(executingNotification));

_logger.LogDebug($"Job {_jobName} Completed");

}
catch (Exception ex)
{
await _eventAggregator.PublishAsync(new Notifications.RecurringBackgroundJobFailedNotification(_job, new EventMessages()).WithStateFrom(executingNotification));
_logger.LogError(ex, "Unhandled exception in recurring background job.");
_logger.LogError(ex, $"Unhandled exception in {_jobName} recurring background job.");
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,19 @@ public RecurringBackgroundJobHostedServiceRunner(
_jobFactory = jobFactory;
}

private static string PrettyName(Type type)
{
if (type.GetGenericArguments().Length == 0)
{
return type.Name;
}
var genericArguments = type.GetGenericArguments();
var typeDefinition = type.Name;
var unmangledName = typeDefinition.Substring(0, typeDefinition.IndexOf("`"));
return unmangledName + "<" + String.Join(",", genericArguments.Select(PrettyName)) + ">";
}


public async Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Creating recurring background jobs hosted services");
Expand All @@ -44,12 +57,12 @@ public async Task StartAsync(CancellationToken cancellationToken)
{
try
{
_logger.LogInformation($"Starting background hosted service for {hostedService.GetType().Name}");
_logger.LogInformation($"Starting background hosted service for {PrettyName(hostedService.GetType())}");
await hostedService.StartAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception exception)
{
_logger.LogError(exception, $"Failed to start background hosted service for {hostedService.GetType().Name}");
_logger.LogError(exception, $"Failed to start background hosted service for {PrettyName(hostedService.GetType())}");
}
}

Expand All @@ -66,12 +79,12 @@ public async Task StopAsync(CancellationToken stoppingToken)
{
try
{
_logger.LogInformation($"Stopping background hosted service for {hostedService.GetType().Name}");
_logger.LogInformation($"Stopping background hosted service for {PrettyName(hostedService.GetType())}");
await hostedService.StopAsync(stoppingToken).ConfigureAwait(false);
}
catch (Exception exception)
{
_logger.LogError(exception, $"Failed to stop background hosted service for {hostedService.GetType().Name}");
_logger.LogError(exception, $"Failed to stop background hosted service for {PrettyName(hostedService.GetType())}");
}
}

Expand Down