improve HostedServiceBase so that scheduled jobs can be registered during installation

This commit is contained in:
sbwalker 2025-02-18 11:35:38 -05:00
parent 5e147afb9f
commit f158a222f4

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
@ -45,28 +46,61 @@ namespace Oqtane.Infrastructure
protected async Task ExecuteAsync(CancellationToken stoppingToken)
{
await Task.Yield(); // required so that this method does not block startup
while (!stoppingToken.IsCancellationRequested)
{
using (var scope = _serviceScopeFactory.CreateScope())
{
IConfigurationRoot _config = scope.ServiceProvider.GetRequiredService<IConfigurationRoot>();
ILogger<HostedServiceBase> _filelogger = scope.ServiceProvider.GetRequiredService<ILogger<HostedServiceBase>>();
// if framework is installed
if (IsInstalled(_config))
{
try
{
var jobs = scope.ServiceProvider.GetRequiredService<IJobRepository>();
// get name of job
string jobTypeName = Utilities.GetFullTypeName(GetType().AssemblyQualifiedName);
// load jobs and find current job
Job job = jobs.GetJobs().Where(item => item.JobType == jobTypeName).FirstOrDefault();
if (job == null)
{
// auto registration
job = new Job { JobType = jobTypeName };
// optional HostedServiceBase properties
var jobType = Type.GetType(jobTypeName);
var jobObject = ActivatorUtilities.CreateInstance(scope.ServiceProvider, jobType) as HostedServiceBase;
if (jobObject.Name != "")
{
job.Name = jobObject.Name;
}
else
{
job.Name = Utilities.GetTypeName(job.JobType);
}
job.Frequency = jobObject.Frequency;
job.Interval = jobObject.Interval;
job.StartDate = jobObject.StartDate;
job.EndDate = jobObject.EndDate;
job.RetentionHistory = jobObject.RetentionHistory;
job.IsEnabled = jobObject.IsEnabled;
job.IsStarted = true;
job.IsExecuting = false;
job.NextExecution = null;
job = jobs.AddJob(job);
}
if (job != null && job.IsEnabled && !job.IsExecuting)
{
var jobLogs = scope.ServiceProvider.GetRequiredService<IJobLogRepository>();
var tenantRepository = scope.ServiceProvider.GetRequiredService<ITenantRepository>();
var tenantManager = scope.ServiceProvider.GetRequiredService<ITenantManager>();
// get name of job
string jobType = Utilities.GetFullTypeName(GetType().AssemblyQualifiedName);
// load jobs and find current job
Job job = jobs.GetJobs().Where(item => item.JobType == jobType).FirstOrDefault();
if (job != null && job.IsEnabled && !job.IsExecuting)
{
// get next execution date
DateTime NextExecution;
if (job.NextExecution == null)
@ -146,9 +180,6 @@ namespace Oqtane.Infrastructure
}
}
catch (Exception ex)
{
// can occur during the initial installation because the database has not yet been created
if (!ex.Message.Contains("No database provider has been configured for this DbContext"))
{
_filelogger.LogError(Utilities.LogMessage(this, $"An Error Occurred Executing Scheduled Job: {Name} - {ex}"));
}
@ -208,9 +239,12 @@ namespace Oqtane.Infrastructure
{
using (var scope = _serviceScopeFactory.CreateScope())
{
IConfigurationRoot _config = scope.ServiceProvider.GetRequiredService<IConfigurationRoot>();
ILogger<HostedServiceBase> _filelogger = scope.ServiceProvider.GetRequiredService<ILogger<HostedServiceBase>>();
try
{
if (IsInstalled(_config))
{
string jobTypeName = Utilities.GetFullTypeName(GetType().AssemblyQualifiedName);
IJobRepository jobs = scope.ServiceProvider.GetRequiredService<IJobRepository>();
@ -222,43 +256,13 @@ namespace Oqtane.Infrastructure
job.IsExecuting = false;
jobs.UpdateJob(job);
}
else
{
// auto registration - job will not run on initial installation due to no DBContext but will run after restart
job = new Job { JobType = jobTypeName };
// optional HostedServiceBase properties
var jobType = Type.GetType(jobTypeName);
var jobObject = ActivatorUtilities.CreateInstance(scope.ServiceProvider, jobType) as HostedServiceBase;
if (jobObject.Name != "")
{
job.Name = jobObject.Name;
}
else
{
job.Name = Utilities.GetTypeName(job.JobType);
}
job.Frequency = jobObject.Frequency;
job.Interval = jobObject.Interval;
job.StartDate = jobObject.StartDate;
job.EndDate = jobObject.EndDate;
job.RetentionHistory = jobObject.RetentionHistory;
job.IsEnabled = jobObject.IsEnabled;
job.IsStarted = true;
job.IsExecuting = false;
job.NextExecution = null;
jobs.AddJob(job);
}
}
catch (Exception ex)
{
// can occur during the initial installation because the database has not yet been created
if (!ex.Message.Contains("No database provider has been configured for this DbContext"))
{
_filelogger.LogError(Utilities.LogMessage(this, $"An Error Occurred Starting Scheduled Job: {Name} - {ex}"));
}
}
}
_executingTask = ExecuteAsync(_cancellationTokenSource.Token);
@ -314,6 +318,11 @@ namespace Oqtane.Infrastructure
}
}
private bool IsInstalled(IConfigurationRoot config)
{
return !string.IsNullOrEmpty(config.GetConnectionString(SettingKeys.ConnectionStringKey));
}
public void Dispose()
{
_cancellationTokenSource.Cancel();