c# 任务调度篇QuartZ(第二部分:框架日志和监听)

执行代码

public static async Task Init()
        {

            #region 获取框架日志
            LogProvider.SetCurrentLogProvider(new CustomConsoleLogProvider());//
            #endregion

            #region Scheduler

            StdSchedulerFactory factory = new StdSchedulerFactory();
            IScheduler scheduler = await factory.GetScheduler();
            await scheduler.Start();

         
             
            #region Listener
            scheduler.ListenerManager.AddJobListener(new CustomJobListener());
            scheduler.ListenerManager.AddTriggerListener(new CustomTriggerListener());
            scheduler.ListenerManager.AddSchedulerListener(new CustomSchedulerListener());
            #endregion

            #endregion

            #region JobDetail
            IJobDetail jobDetail = JobBuilder.Create<SendMessage>()
                  .WithIdentity("sendJob", "group1")
                  .WithDescription("This is sendJob")
                  .Build();

            jobDetail.JobDataMap.Add("Student1", "阳光下的微笑");
            jobDetail.JobDataMap.Add("Student2", "明日梦");
            jobDetail.JobDataMap.Add("Student3", "大白");
            jobDetail.JobDataMap.Add("Student4", "池鱼");

            jobDetail.JobDataMap.Add("Year", DateTime.Now.Year);

            #endregion

            #region trigger

            //ITrigger trigger = TriggerBuilder.Create()
            //               .WithIdentity("sendTrigger", "group1")
            //               //.StartAt(new DateTimeOffset(DateTime.Now.AddSeconds(10)))
            //               .StartNow()
            //              .WithCronSchedule("5/3 * * * * ?")//每隔一分钟 
            //              //5,8,11,14
            //              .WithDescription("This is sendJob's sendTrigger")
            //              .Build();

            ITrigger trigger = TriggerBuilder.Create()
                   .WithIdentity("sendTrigger", "group1")
                   .StartNow()
                   .WithSimpleSchedule(x => x
                       .WithIntervalInSeconds(10) //多少秒执行一次 
                       .WithRepeatCount(10) //表示最多执行多少次
                       .RepeatForever())
                       .WithDescription("This is testjob's Trigger")
                   .Build();

            trigger.JobDataMap.Add("Student5", "非常Nice");
            trigger.JobDataMap.Add("Student6", "Jerry");
            trigger.JobDataMap.Add("Student7", "龙");
            trigger.JobDataMap.Add("Student8", "月光寒");
            trigger.JobDataMap.Add("Year", DateTime.Now.Year + 1);

            #endregion 

            await scheduler.ScheduleJob(jobDetail, trigger);
        }
    }

监听Job,Trigger,Scheduler

public class CustomJobListener : IJobListener
    {
        public string Name => "CustomJobListener";

        public async Task JobExecutionVetoed(IJobExecutionContext context, CancellationToken cancellationToken = default)
        {
            await Task.Run(() =>
            {
                //便于我们自己添加自己的业务逻辑
                Console.WriteLine($"{DateTime.Now} this is JobExecutionVetoed");
            });
        }
         
        public async Task JobToBeExecuted(IJobExecutionContext context, CancellationToken cancellationToken = default)
        {
            await Task.Run(() =>
            {
                Console.WriteLine($"{DateTime.Now} this is JobToBeExecuted");
            });
        }

        public async Task JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException, CancellationToken cancellationToken = default)
        {
            await Task.Run(() =>
            {
                Console.WriteLine($"{DateTime.Now} this is JobWasExecuted");
            });
        }
    }
public class CustomSchedulerListener : ISchedulerListener
    {
        public async Task JobAdded(IJobDetail jobDetail, CancellationToken cancellationToken = default)
        {
            await Task.Run(() =>
            {
                Console.WriteLine($"{jobDetail.Description} 被加入到Scheduler");
            });
        }

        public async Task JobDeleted(JobKey jobKey, CancellationToken cancellationToken = default)
        {
            await Task.Run(() =>
            {
                Console.WriteLine($"{jobKey} 被删除 ");
            });
        }

        public Task JobInterrupted(JobKey jobKey, CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }

        public Task JobPaused(JobKey jobKey, CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }

        public Task JobResumed(JobKey jobKey, CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }

        public async Task JobScheduled(ITrigger trigger, CancellationToken cancellationToken = default)
        {
            await Task.Run(() =>
            {
                Console.WriteLine("this is JobScheduled");
            });
        }

        public Task JobsPaused(string jobGroup, CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }

        public Task JobsResumed(string jobGroup, CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }

        public Task JobUnscheduled(TriggerKey triggerKey, CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }

        public Task SchedulerError(string msg, SchedulerException cause, CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }

        public Task SchedulerInStandbyMode(CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }

        public Task SchedulerShutdown(CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }

        public Task SchedulerShuttingdown(CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }

        public async Task SchedulerStarted(CancellationToken cancellationToken = default)
        {
            await Task.Run(() =>
            {
                Console.WriteLine($"this is SchedulerStarted");
            });
        }

        public async Task SchedulerStarting(CancellationToken cancellationToken = default)
        {
            await Task.Run(() =>
            {
                Console.WriteLine($"this is SchedulerStarting");
            });
        }

        public Task SchedulingDataCleared(CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }

        public Task TriggerFinalized(ITrigger trigger, CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }

        public Task TriggerPaused(TriggerKey triggerKey, CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }

        public Task TriggerResumed(TriggerKey triggerKey, CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }

        public Task TriggersPaused(string triggerGroup, CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }

        public Task TriggersResumed(string triggerGroup, CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }
    }
public class CustomTriggerListener : ITriggerListener
    {
        public string Name => "CustomTriggerListener";

        public async Task TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode, CancellationToken cancellationToken = default)
        {
            await Task.Run(() =>
            { 
                Console.WriteLine("this is TriggerComplete");
            });
        }

        public async Task TriggerFired(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default)
        {
            await Task.Run(() =>
            {
                Console.WriteLine("this is TriggerFired");
            });
        }

        public async Task TriggerMisfired(ITrigger trigger, CancellationToken cancellationToken = default)
        {
            await Task.Run(() =>
            {
                Console.WriteLine("this is TriggerComplete");
            });
        }

        public async Task<bool> VetoJobExecution(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default)
        {
            await Task.Run(() =>
            {
                Console.WriteLine("VetoJobExecution");
            });
            return false;  //返回false才能继续执行
        }
    }

框架日志

public class CustomConsoleLogProvider : ILogProvider
    {
        public Logger GetLogger(string name) ///可以获取到框架内部的日志信息
        {
            return new Logger((level, func, exception, parameters) =>
            {
                if (level >= LogLevel.Info && func != null)
                {
                    Console.WriteLine($"[{ DateTime.Now.ToLongTimeString()}] [{ level}] { func()} {string.Join(";", parameters.Select(p => p == null ? " " : p.ToString()))}  自定义日志{name}");
                }
                return true;
            });
        }
        public IDisposable OpenNestedContext(string message)
        {
            throw new NotImplementedException();
        }

        public IDisposable OpenMappedContext(string key, string value)
        {
            throw new NotImplementedException();
        }
    }
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页