.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);
    }
}
相关推荐
花之亡灵2 小时前
.net 6 + vue3中使用SignaIR实现双向通信功能
前端·javascript·笔记·websocket·.net·信息与通信
步、步、为营17 小时前
ShapeCrawler:.NET开发者的PPTX操控魔法
.net
烟锁池塘柳020 小时前
.NET三层架构详解
架构·.net
界面开发小八哥1 天前
智能仪表板DevExpress Dashboard v24.2新版亮点:支持.NET 9
.net·界面控件·devexpress·用户界面
EdisonZhou1 天前
2025成都.NET开发者Connect圆满结束
aigc·.net·敏捷开发·社区活动
追逐时光者2 天前
精选15款C#/.NET编程效率提升类库,含详细使用教程!
后端·.net
公子小六2 天前
ASP.NET Core WebApi+React UI开发入门详解
react.js·ui·c#·asp.net·.netcore
Long_poem2 天前
【自学笔记】.NET基础知识点总览-持续更新
笔记·.net
工藤新一OL2 天前
.netCore的winform程序如何调用webapi
c#·.net·.netcore·visual studio
追逐时光者3 天前
C# 13 中的新增功能实操
后端·.net