Skip to content

Commit

Permalink
Make UseNCronJobAsync() mandatory when startup jobs have been defined
Browse files Browse the repository at this point in the history
  • Loading branch information
nulltoken committed Nov 5, 2024
1 parent c59e568 commit 97f7348
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 5 deletions.
3 changes: 0 additions & 3 deletions src/NCronJob/Scheduler/QueueWorker.LogMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,4 @@ internal sealed partial class QueueWorker

[LoggerMessage(LogLevel.Information, "Job removed from queue: {JobType} at {RunAt}")]
private partial void LogJobRemovedFromQueue(string jobType, DateTime? runAt);

[LoggerMessage(LogLevel.Warning, "The UseNCronJob(Async) method was not called. Startup jobs might not have been executed.")]
private partial void LogUseNCronJobNotCalled();
}
14 changes: 12 additions & 2 deletions src/NCronJob/Scheduler/QueueWorker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,10 +122,20 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)

private void AssertUseNCronJobWasCalled()
{
if (!missingMethodCalledHandler.UseWasCalled)
if (missingMethodCalledHandler.UseWasCalled)
{
LogUseNCronJobNotCalled();
return;
}

if (jobRegistry.GetAllOneTimeJobs().Count == 0)
{
return;
}

throw new InvalidOperationException(
$"""
Startup jobs have been registered. However, neither IHost.UseNCronJobAsync(), nor IHost.UseNCronJob() have been been called.
""");
}

private void CreateWorkerQueues(CancellationToken stopToken)
Expand Down
20 changes: 20 additions & 0 deletions tests/NCronJob.Tests/RunAtStartupJobTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,26 @@ namespace NCronJob.Tests;

public class RunAtStartupJobTests : JobIntegrationBase
{
[Fact]
public async Task UseNCronJobIsMandatoryWhenStartupJobsAreDefined()
{
var builder = Host.CreateDefaultBuilder();
var storage = new Storage();
builder.ConfigureServices(services =>
{
services.AddNCronJob(s => s.AddJob<SimpleJob>().RunAtStartup());
services.AddSingleton(_ => storage);
});

using var app = builder.Build();

#pragma warning disable IDISP013 // Await in using
Func<Task> act = () => RunApp(app);
#pragma warning restore IDISP013 // Await in using

await act.ShouldThrowAsync<InvalidOperationException>();
}

[Fact]
public async Task UseNCronJobShouldTriggerStartupJobs()
{
Expand Down

0 comments on commit 97f7348

Please sign in to comment.