0
点赞
收藏
分享

微信扫一扫

.net5 quartz

  1. 安装quartz.aspnetcore
  2. ConfigureServices中注入

//services.AddHostedService<Worker>();
services.AddQuartz(q =>
{
//依赖注入
q.UseMicrosoftDependencyInjectionJobFactory();


// 基本Quartz调度器、作业和触发器配置
var jobKey = new JobKey("jobname", "groupName");
q.AddJob<TestJob>(jobKey, j => j
.WithDescription("My work")
);
q.AddTrigger(t => t
.WithIdentity("x")
.ForJob(jobKey)
.StartNow()
.WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(2))
.RepeatForever())//持续工作
.WithDescription("My work trigger")
);


});

// ASP.NET核心托管-添加Quartz服务器
services.AddQuartzServer(options =>
{
// 关闭时,我们希望作业正常完成
options.WaitForJobsToComplete = false;
});

TestJob内容如下

public class TestJob : IBaseJob
{
public virtual Task Execute(IJobExecutionContext context)
{
return Console.Out.WriteLineAsync($"job工作了 在{DateTime.Now}");
}

动态添加计划

public async void Start()
{
// 1.创建scheduler的引用
ISchedulerFactory schedFact = new StdSchedulerFactory();
IScheduler sched = await schedFact.GetScheduler();

//2.启动 scheduler
await sched.Start();

// 3.创建 job
IJobDetail job = JobBuilder.Create<TestJob>()
.WithIdentity("job1", "group1")
.Build();

// 4.创建 trigger
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
//.WithSimpleSchedule(x => x.WithIntervalInSeconds(1).RepeatForever())
.WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever())
.Build();

// 5.使用trigger规划执行任务job
await sched.ScheduleJob(job, trigger);
}

quartz传递参数

可以通过SetJobData来传递一个JobDataMap类型的参数

 quartz.AddJob<T>(jobKey, j =>
{
j.SetJobData(new JobDataMap
{
{"id", "test"},
});
}
);

扩展封装

public static class QuartzEx
{
public static void addSchedule<T>(this IServiceCollectionQuartzConfigurator quartz, string id, string groupName, string desc, int intervalSecond, JobDataMap newJobDataMap) where T : IJob
{
// 基本Quartz调度器、作业和触发器配置
JobKey jobKey = new JobKey(nameof(T), groupName);
quartz.AddJob<T>(jobKey, j =>
{
j.WithDescription(desc);
j.SetJobData(newJobDataMap);
}
);
quartz.AddTrigger(t => t
.WithIdentity(id)
.ForJob(jobKey)
.StartNow()
.WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(intervalSecond))
.RepeatForever())//持续工作
.WithDescription(desc)
);
}
}

[参考]
​​​ASP.NET Core定时之Quartz.NET使用​​​​官网​​


举报

相关推荐

0 条评论