.NET8 动态添加定时任务(CRON Expression, Whatever)

需要使用 Quartz .NET

csharp 复制代码
 <PackageReference Include="Quartz.AspNetCore"/>

建立 Global JobKey

csharp 复制代码
public static class GlobalJobKey
{
    public static JobKey CustomizedKey => new JobKey("xxx scheduled", "group1");
}

建立 Job

csharp 复制代码
public class CustomizedJob : IJob
{
    public async Task Execute(IJobExecutionContext context)
    {
        // pass the parameter if you want,
        // depends on your business logic
        var customizedData =
            JsonSerializer.Deserialize<YourType>(context.MergedJobDataMap.Get("data").ToString()!);
      	// your logic
    }
}

在 Program.cs 中配置 Quartz .NET

csharp 复制代码
// construct the Quartz Trigger
builder.Services.AddQuartz(q =>
{
	q.AddJob<CustomizedJob>(opt => { opt.WithIdentity(GlobalJobKey.CustomizedKey).StoreDurably(); });
});

builder.Services.AddQuartzHostedService(options => { options.WaitForJobsToComplete = true; });

builder.Services.AddScoped<IJob, CustomizedJob>();

可以在任意地方: Controller, Background Service, Service... 中进行配置

csharp 复制代码
public class CustomizedBackgroundService(
    ISchedulerFactory factory,
    IServiceScopeFactory scopeFactory,
    ILogger<CustomizedBackgroundService> logger) : IHostedService
{
    private IScheduler? Schedule { get; set; }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        if (Schedule != null)
        {
            await StopJobs(cancellationToken);
        }

        using var scope = scopeFactory.CreateScope();
        var repo = scope.ServiceProvider.GetRequiredService<CustomizedRepository>();
        var configurations = (await repo.Query()).ToArray();
        Schedule = await factory.GetScheduler(cancellationToken);
        await Schedule.Start(cancellationToken);
        var jobDetail = JobBuilder.Create<CustomizedJob>()
            .WithIdentity(GlobalJobKey.CustomizedKey)
            .StoreDurably()
            .Build();

        await Schedule.AddJob(jobDetail, true, cancellationToken);

        Array.ForEach(configurations, Action);

        return;

        async void Action(CustomizedConfiguration configuration)
        {

            var triggerKey = new TriggerKey($"{configuration.Name}-trigger", "group1");

            var existingTrigger = await Schedule.GetTrigger(triggerKey, cancellationToken);
            if (existingTrigger != null)
                await Schedule.UnscheduleJob(triggerKey, cancellationToken);
            var trigger = TriggerBuilder.Create()
                .WithIdentity(triggerKey)
                .ForJob(GlobalJobKey.CustomizedKey)
         		.WithCronSchedule("0 0 0 ? * 1")
                .UsingJobData("data", JsonSerializer.Serialize(configuration))
                .StartNow()
                .Build();

            await Schedule.ScheduleJob(trigger, cancellationToken);

            logger.LogCritical("add trigger for: {Trigger}", $"{configuration.Name}-trigger");
        }
    }

    public async Task StopAsync(CancellationToken cancellationToken)
    {
        if (Schedule != null)
        {
            await StopJobs(cancellationToken);
        }
    }

    private async Task StopJobs(CancellationToken cancellationToken)
    {
        await Schedule?.Shutdown(cancellationToken)!;
        Schedule?.Clear(cancellationToken);
    }
}
相关推荐
dot.Net安全矩阵4 分钟前
.NET 通过模块和驱动收集本地EDR的工具
windows·安全·web安全·.net·交互
zls3653655 分钟前
.NET开源实时应用监控系统:WatchDog
.net
djk888811 分钟前
.net将List<实体1>的数据转到List<实体2>
数据结构·list·.net
Crazy Struggle5 小时前
功能齐全的 WPF 自定义控件资源库(收藏版)
.net·wpf·ui控件库
时光追逐者7 小时前
.NET 9 中 LINQ 新增功能实操
开发语言·开源·c#·.net·.netcore·linq·微软技术
zls36536510 小时前
.NET高效下载word文件
开发语言·c#·word·.net
八荒我为王11 小时前
c#编码技巧(十九):各种集合特点汇总
c#·.net
桑榆肖物13 小时前
将 .NET Aspire 添加到现有应用:前端 JavaScript 项目处理
前端·javascript·.net
shepherd枸杞泡茶19 小时前
WPF动画
c#·.net·wpf
Crazy Struggle1 天前
C# 开发的环境监测上位机应用
c#·.net·上位机·上位机软件