48 lines
		
	
	
		
			1.4 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
			
		
		
	
	
			48 lines
		
	
	
		
			1.4 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
| using System;
 | |
| using Microsoft.Extensions.DependencyInjection;
 | |
| 
 | |
| namespace StellaOps.Concelier.Core.Jobs;
 | |
| 
 | |
| public sealed class JobSchedulerBuilder
 | |
| {
 | |
|     private readonly IServiceCollection _services;
 | |
| 
 | |
|     public JobSchedulerBuilder(IServiceCollection services)
 | |
|     {
 | |
|         _services = services ?? throw new ArgumentNullException(nameof(services));
 | |
|     }
 | |
| 
 | |
|     public JobSchedulerBuilder AddJob<TJob>(
 | |
|         string kind,
 | |
|         string? cronExpression = null,
 | |
|         TimeSpan? timeout = null,
 | |
|         TimeSpan? leaseDuration = null,
 | |
|         bool enabled = true)
 | |
|         where TJob : class, IJob
 | |
|     {
 | |
|         ArgumentException.ThrowIfNullOrEmpty(kind);
 | |
| 
 | |
|         _services.AddTransient<TJob>();
 | |
|         _services.Configure<JobSchedulerOptions>(options =>
 | |
|         {
 | |
|             if (options.Definitions.ContainsKey(kind))
 | |
|             {
 | |
|                 throw new InvalidOperationException($"Job '{kind}' is already registered.");
 | |
|             }
 | |
| 
 | |
|             var resolvedTimeout = timeout ?? options.DefaultTimeout;
 | |
|             var resolvedLease = leaseDuration ?? options.DefaultLeaseDuration;
 | |
| 
 | |
|             options.Definitions.Add(kind, new JobDefinition(
 | |
|                 kind,
 | |
|                 typeof(TJob),
 | |
|                 resolvedTimeout,
 | |
|                 resolvedLease,
 | |
|                 cronExpression,
 | |
|                 enabled));
 | |
|         });
 | |
| 
 | |
|         return this;
 | |
|     }
 | |
| }
 |