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 70a0394 commit 679a271
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 5 deletions.
2 changes: 2 additions & 0 deletions docs/features/startup-jobs.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ app.Run();

The `RunAtStartup` in combination with `UseNCronJobAsync` method ensures that the job is executed as soon as the application starts. This method is useful for scenarios where certain tasks need to be performed immediately upon application launch.

Failure to call `UseNCronJobAsync` when startup jobs are defined will lead to a fatal exception during the application start.

## Example Use Case

Consider an application that needs to load initial data from a database or perform some cleanup tasks whenever it starts. You can define and configure a startup job to handle this:
Expand Down
6 changes: 6 additions & 0 deletions src/NCronJob/NCronJobExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,12 +116,18 @@ public static IServiceCollection AddNCronJob(this IServiceCollection services, D
/// <summary>
/// Configures the host to use NCronJob. This will also start any given startup jobs and their dependencies.
/// </summary>
/// <remarks>
/// Failure to call this method (or <see cref="UseNCronJobAsync(IHost)"/>) when startup jobs are defined will lead to a fatal exception during the application start.
/// </remarks>
/// <param name="host">The host.</param>
public static IHost UseNCronJob(this IHost host) => UseNCronJobAsync(host).ConfigureAwait(false).GetAwaiter().GetResult();

/// <summary>
/// Configures the host to use NCronJob. This will also start any given startup jobs and their dependencies.
/// </summary>
/// <remarks>
/// Failure to call this method (or <see cref="UseNCronJob(IHost)"/>) when startup jobs are defined will lead to a fatal exception during the application start.
/// </remarks>
/// <param name="host">The host.</param>
public static async Task<IHost> UseNCronJobAsync(this IHost host)
{
Expand Down
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 679a271

Please sign in to comment.