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

目录

创建简易控制台定时任务

步骤

  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粘贴官网示例
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!");
        }
    }
}
  • 运行控制台程序

    说明:
    info是日志插件输出的
    hellojob就是任务触发的
  1. 添加触发监听器
cs 复制代码
//触发器执行前
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)
{}
  • 主程序中添加触发监听器
cs 复制代码
           // 将trigger监听器注册到调度器
            scheduler.ListenerManager.AddTriggerListener(new CustomTriggerListener());

完整程序

  • Program.cs
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));
        }
    }
}
  • CustomTriggerListener.cs
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;
        }
    }

}
相关推荐
-凌凌漆-31 分钟前
【Qt】QStringLiteral 介绍
开发语言·qt
程序员爱钓鱼31 分钟前
Go语言项目工程化 — 常见开发工具与 CI/CD 支持
开发语言·后端·golang·gin
军训猫猫头1 小时前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
真的想上岸啊1 小时前
学习C++、QT---18(C++ 记事本项目的stylesheet)
开发语言·c++·学习
明天好,会的1 小时前
跨平台ZeroMQ:在Rust中使用zmq库的完整指南
开发语言·后端·rust
追逐时光者2 小时前
C#/.NET/.NET Core优秀项目和框架2025年6月简报
后端·.net
丁劲犇2 小时前
用 Turbo Vision 2 为 Qt 6 控制台应用创建 TUI 字符 MainFrame
开发语言·c++·qt·tui·字符界面·curse
旷世奇才李先生2 小时前
Next.js 安装使用教程
开发语言·javascript·ecmascript
charlie1145141913 小时前
深入理解Qt的SetWindowsFlags函数
开发语言·c++·qt·原理分析
likeGhee4 小时前
python缓存装饰器实现方案
开发语言·python·缓存