29 lines
878 B
C#
29 lines
878 B
C#
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Hosting;
|
|
|
|
namespace ScheduledService;
|
|
|
|
public static class ScheduledServiceExtensions
|
|
{
|
|
public static IServiceCollection AddCronJob<T>(this IServiceCollection services, Action<IScheduleConfig<T>> options) where T : CronJobService
|
|
{
|
|
if (options == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(options), "Options cannot be null");
|
|
}
|
|
|
|
var config = new ScheduleConfig<T>();
|
|
options.Invoke(config);
|
|
|
|
if (string.IsNullOrWhiteSpace(config.CronExpression))
|
|
{
|
|
throw new ArgumentNullException(nameof(ScheduleConfig<T>.CronExpression), "Cron expression cannot be null or empty");
|
|
}
|
|
|
|
services.AddSingleton<IScheduleConfig<T>>(config);
|
|
services.AddHostedService<T>();
|
|
|
|
return services;
|
|
}
|
|
}
|