-5 quartz
安装quartz.aspnetcoreConfigureServices中注入
//services.AddHostedService(); services.AddQuartz(q => { //依赖注入 q.UseMicrosoftDependencyInjectionJobFactory(); // 基本Quartz调度器、作业和触发器配置 var jobKey = new JobKey("jobname", "groupName"); q.AddJob(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() .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(jobKey, j => { j.SetJobData(new JobDataMap { {"id", "test"}, }); } );
扩展封装
public static class QuartzEx { public static void addSchedule(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(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使用官网
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~