.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);
    }
}
相关推荐
九鼎科技-Leo8 小时前
了解 .NET 运行时与 .NET 框架:基础概念与相互关系
windows·c#·.net
九鼎科技-Leo10 小时前
什么是 ASP.NET Core?与 ASP.NET MVC 有什么区别?
windows·后端·c#·asp.net·mvc·.net
.net开发11 小时前
WPF怎么通过RestSharp向后端发请求
前端·c#·.net·wpf
九鼎科技-Leo15 小时前
在 C# 中,ICollection 和 IList 接口有什么区别?
windows·c#·.net
时光追逐者15 小时前
C#/.NET/.NET Core学习路线集合,学习不迷路!
开发语言·学习·c#·asp.net·.net·.netcore·微软技术
Crazy Struggle18 小时前
.NET 全功能流媒体管理控制接口平台
.net·开源项目·流媒体
.net开发18 小时前
WPF使用prism框架发布订阅实现消息提示
c#·.net·wpf
慧都小妮子1 天前
FastReport将停止 .NET Framework 上的 WebReport 更新
.net·报表控件·fastreport
Jeffrey侠客1 天前
.Net Core 6.0 WebApi在Centos中部署
linux·centos·.netcore