c# Quartz 简单使用
public class ActionJob : IJob { public static Dictionary<string, Action<object>> ActionList { get; } = new Dictionary<string, Action<object>>(); public Task Execute(IJobExecutionContext context) { return Task.Run(() => { JobDataMap dataMap = context.JobDetail.JobDataMap; string name = dataMap.GetString("key"); object value = dataMap.Get("value"); if (ActionList.ContainsKey(name)) { ActionList[name]?.Invoke(value); } }); } public static async void CreateJob(Action<object> action, string key, string value, ITrigger trigger) { var scheduler = await StdSchedulerFactory.GetDefaultScheduler(); if (!scheduler.IsStarted) { await scheduler.Start(); } ActionList.Add(key, action); IJobDetail job = JobBuilder.Create<ActionJob>() .WithIdentity(new JobKey(key)) // name "myJob", group "group1" .UsingJobData("key", key) .UsingJobData("value", value) .Build(); await scheduler.ScheduleJob(job, trigger); //把作业,触发器加入调度器。 } public static void CreateJob(Action<object> action, string key, string value, int seconds) { // 创建触发器 ITrigger trigger = TriggerBuilder.Create() .StartNow() //现在开始 .WithSimpleSchedule(x => x .WithIntervalInSeconds(seconds) .RepeatForever()) .Build(); CreateJob(action, key, value, trigger); } public static async void Remove(string key) { var scheduler = await StdSchedulerFactory.GetDefaultScheduler(); await scheduler.DeleteJob(new JobKey(key)); ActionList.Remove(key); } }
创建一个一秒输出当前时间定时器:
ActionJob.CreateJob(value=> Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss}") , "writeTime", null, 1);
第三个参数支持传一个string,传了之后会在第一个参数中value返回
移除当前定时器
ActionJob.Remove("writeTime");
原文:https://www.cnblogs.com/zisai/p/13560832.html