.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);
    }
}
相关推荐
code_shenbing7 小时前
.NET MVC实现电影票管理
mvc·.net
shepherd枸杞泡茶11 小时前
第3章 3.3日志 .NET Core日志 NLog使用教程
c#·asp.net·.net·.netcore
csdn_aspnet11 小时前
ASP.NET Core 简单文件上传
asp.net·.netcore
时光追逐者1 天前
推荐几款开源免费的 .NET MAUI 组件库
microsoft·开源·c#·.net·.net core·maui
三天不学习1 天前
.Net面试宝典【刷题系列】
面试·职场和发展·.net
JosieBook1 天前
【.NET全栈】.NET包含的所有技术
.net
shepherd枸杞泡茶1 天前
第3章 3.2 配置系统 .NET Core配置系统
后端·c#·asp.net·.net
追逐时光者2 天前
Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
后端·.net
CodeCraft Studio2 天前
文档处理控件TX Text Control系列教程:使用 .NET C# 从 PDF 文档中提取基于模板的文本
pdf·c#·.net
Crazy Struggle2 天前
.NET 使用 DeepSeek R1 开发智能 AI 客户端
人工智能·ai·.net·deepseek