Skip to content
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

Make UseNCronJobAsync() mandatory when startup jobs have been defined #136

Merged
merged 1 commit into from
Nov 5, 2024
Merged
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
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(
linkdotnet marked this conversation as resolved.
Show resolved Hide resolved
$"""
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