• 使用C#插件Quartz.Net定时执行CMD任务工具2


    创建简易控制台定时任务

    • 创建winform的可以看:https://blog.csdn.net/wayhb/article/details/134279205

    步骤

    1. 创建控制台程序
    • 使用vs2019
    • 新建项目,控制台程序,使用.net4.7.2
    • 项目右键(管理NuGet程序包),搜索Quartz,安装
      在这里插入图片描述
    1. 使用Quartz.Net官网示例运行程序
    • 打开官网https://www.quartz-scheduler.net/documentation/quartz-3.x/quick-start.html#trying-out-the-application,在程序入库Program.cs粘贴官网示例
    //出现错误右键修复,自动添加包
    using Quartz;
    using Quartz.Impl;
    using Quartz.Logging;
    using System;
    using System.Threading.Tasks;
    
    namespace ConsoleSkWork
    {
        class Program
        {
            private static async Task Main(string[] args)
            {
                LogProvider.SetCurrentLogProvider(new ConsoleLogProvider());
    
                // Grab the Scheduler instance from the Factory
                StdSchedulerFactory factory = new StdSchedulerFactory();
                IScheduler scheduler = await factory.GetScheduler();
    
                // and start it off
                await scheduler.Start();
    
                // define the job and tie it to our HelloJob class
                IJobDetail job = JobBuilder.Create<HelloJob>()
                    .WithIdentity("job1", "group1")
                    .Build();
    
                // Trigger the job to run now, and then repeat every 10 seconds
                ITrigger trigger = TriggerBuilder.Create()
                    .WithIdentity("trigger1", "group1")
                    .StartNow()
                    .WithSimpleSchedule(x => x
                        .WithIntervalInSeconds(10)
                        .RepeatForever())
                    .Build();
    
                // Tell Quartz to schedule the job using our trigger
                await scheduler.ScheduleJob(job, trigger);
    
                // some sleep to show what's happening
                await Task.Delay(TimeSpan.FromSeconds(60));
    
                // and last shut down the scheduler when you are ready to close your program
                await scheduler.Shutdown();
    
                Console.WriteLine("Press any key to close the application");
                Console.ReadKey();
            }
    
            // simple log provider to get something to the console
            //https://www.quartz-scheduler.net/documentation/quartz-3.x/quick-start.html#trying-out-the-application
            private class ConsoleLogProvider : ILogProvider
            {
                public Logger GetLogger(string name)
                {
                    return (level, func, exception, parameters) =>
                    {
                        if (level >= LogLevel.Info && func != null)
                        {
                            Console.WriteLine("[" + DateTime.Now.ToLongTimeString() + "] [" + level + "] " + func(), parameters);
                        }
                        return true;
                    };
                }
    
                public IDisposable OpenNestedContext(string message)
                {
                    throw new NotImplementedException();
                }
    
                public IDisposable OpenMappedContext(string key, object value, bool destructure = false)
                {
                    throw new NotImplementedException();
                }
            }
        }
    
        public class HelloJob : IJob
        {
            public async Task Execute(IJobExecutionContext context)
            {
                await Console.Out.WriteLineAsync("Greetings from HelloJob!");
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 运行控制台程序
      在这里插入图片描述
      说明:
      info是日志插件输出的
      hellojob就是任务触发的
    1. 添加触发监听器
    • 触发监听器是用于监听触发器的
    • 添加触发监听器可以在任务执行前后执行其他动作,例如输出下一次该任务执行时间
    • 触发监听器官网解释:https://www.quartz-scheduler.net/documentation/quartz-3.x/tutorial/trigger-and-job-listeners.html
    • 继承触发监听器接口有4个方法需要实现
    //触发器执行前
    public async Task TriggerFired(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default)
    {}
    // 判断作业是否继续(true继续,false本次不触发)
    public async Task<bool> VetoJobExecution(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default)
    {}
    //  触发完成
    public async Task TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode, CancellationToken cancellationToken = default)
    {}
    // 触发失败
    public async Task TriggerMisfired(ITrigger trigger, CancellationToken cancellationToken = default)
    {}
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 主程序中添加触发监听器
               // 将trigger监听器注册到调度器
                scheduler.ListenerManager.AddTriggerListener(new CustomTriggerListener());
    
    • 1
    • 2

    完整程序

    • Program.cs
    using System;
    using System.Threading.Tasks;
    
    using Quartz;
    using Quartz.Impl;
    using Quartz.Logging;
    
    namespace ConsoleApp1
    {
        public class Program
        {
            private static async Task Main(string[] args)
            {
                LogProvider.SetCurrentLogProvider(new ConsoleLogProvider());
    
                // Grab the Scheduler instance from the Factory
                StdSchedulerFactory factory = new StdSchedulerFactory();
                IScheduler scheduler = await factory.GetScheduler();
    
                // and start it off
                await scheduler.Start();
    
                // define the job and tie it to our HelloJob class
                IJobDetail job = JobBuilder.Create<HelloJob>()
                    .WithIdentity("job1", "group1")
                    .Build();
    
                // Trigger the job to run now, and then repeat every 10 seconds
                ITrigger trigger = TriggerBuilder.Create()
                    .WithIdentity("trigger1", "group1")
                    .StartNow()
                    .WithSimpleSchedule(x => x
                        .WithIntervalInSeconds(10)
                        .RepeatForever())
                    .Build();
    
                // 将trigger监听器注册到调度器
                scheduler.ListenerManager.AddTriggerListener(new CustomTriggerListener());
    
    
                // Tell Quartz to schedule the job using our trigger
                await scheduler.ScheduleJob(job, trigger);
    
                // some sleep to show what's happening
                await Task.Delay(TimeSpan.FromSeconds(60));
    
                // and last shut down the scheduler when you are ready to close your program
                await scheduler.Shutdown();
    
                Console.WriteLine("Press any key to close the application");
                Console.ReadKey();
            }
    
            // simple log provider to get something to the console
            private class ConsoleLogProvider : ILogProvider
            {
                public Logger GetLogger(string name)
                {
                    return (level, func, exception, parameters) =>
                    {
                        if (level >= LogLevel.Info && func != null)
                        {
                            Console.WriteLine("[" + DateTime.Now.ToLongTimeString() + "] [" + level + "] " + func(), parameters);
                        }
                        return true;
                    };
                }
    
                public IDisposable OpenNestedContext(string message)
                {
                    throw new NotImplementedException();
                }
    
                public IDisposable OpenMappedContext(string key, object value, bool destructure = false)
                {
                    throw new NotImplementedException();
                }
            }
        }
    
        public class HelloJob : IJob
        {
            public async Task Execute(IJobExecutionContext context)
            {
                //获取当前时间
                DateTime currentDateTime = DateTime.UtcNow;
                await Console.Out.WriteLineAsync("当前日期和时间:" + currentDateTime.AddHours(8));
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • CustomTriggerListener.cs
    using Quartz;
    using System;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace ConsoleApp1
    {
    	//继承监听器接口
        public class CustomTriggerListener : ITriggerListener
        {
            public string Name => "CustomTriggerListener";
    
            //触发器执行前
            public async Task TriggerFired(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default)
            {
    
                Console.WriteLine("【*********************************************】");
                Console.WriteLine($"【{Name}】---【TriggerFired】-【触发】");
                await Task.CompletedTask;
            }
    
            // 判断作业是否继续(true继续,false本次不触发)
            public async Task<bool> VetoJobExecution(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default)
            {
    
                Console.WriteLine($"【{Name}】---【VetoJobExecution】-【判断作业是否继续】-{true}");
                return await Task.FromResult(cancellationToken.IsCancellationRequested);
            }
    
            //  触发完成
            public async Task TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode, CancellationToken cancellationToken = default)
            {
                Console.WriteLine($"【{Name}】---【TriggerComplete】-【触发完成】");
                //获取下次执行日期时间UTC,将UTC时间转换成北京时间
                DateTimeOffset dd = (DateTimeOffset)trigger.GetNextFireTimeUtc();
                Console.WriteLine("【下次执行时间:】"+dd.DateTime.AddHours(8));
                await Task.CompletedTask;
            }
    
            // 触发失败
            public async Task TriggerMisfired(ITrigger trigger, CancellationToken cancellationToken = default)
            {
                Console.WriteLine($"【{Name}】---【TriggerMisfired】【触发作业】");
                await Task.CompletedTask;
            }
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
  • 相关阅读:
    Triton推理服务器吞吐量测试
    微服务项目:尚融宝(38)(核心业务流程:申请借款额度(1))
    Spring到底是一个什么东西呢?
    WEB渲染模式——CSR SSR SSG ISR DPR区别
    IK分词器实现原理剖析 —— 一个小问题引发的思考
    三谈大数据之足球盘口赔率水位分析思路及其实现利器
    念一句咒语 AI 就帮我写一个应用,我人麻了...
    cubemx stm32 陶晶驰 串口屏 基于YXY通信原理的串口屏驱动代码
    PGCCC|【PostgreSQL】PCM认证考试大纲#postgresql 认证
    【RV1103】如何新增一个新板级配置
  • 原文地址:https://blog.csdn.net/wayhb/article/details/134432017