随笔 - 26,  文章 - 0,  评论 - 3,  阅读 - 8735

1:首先创建一个控制台应用

代码地址:Quartz代码

2:添加Quartz的NuGet包

 

 

3:创建ConsoleLogProvider和HelloJob类

ConsoleLogProvider:
复制代码
public 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();
        }
复制代码

 

HelloJob:
复制代码
public class HelloJob : IJob
    {
        public async Task Execute(IJobExecutionContext context)
        {
            shixian();
        }

        public async void shixian()
        {
            await Console.Out.WriteLineAsync("实现时间" + DateTime.Now);
            await Console.Out.WriteLineAsync("--------------------------");
            await Console.Out.WriteLineAsync();
        }
    }
复制代码

4:在Program里面添加代码

复制代码
// 从Factory获取Scheduler实例
LogProvider.SetCurrentLogProvider(new ConsoleLogProvider());
StdSchedulerFactory factory = new();
// 从Factory获取Scheduler实例
IScheduler scheduler = await factory.GetScheduler();
Console.WriteLine("下面开始自动化实现代码");
// 开始执行
await scheduler.Start();
//定义job并将其绑定到我们的HelloJob类TJobDetail iob= JobBuilder.CreatesHelloJob>()
//JOB1是定时器的名称  group1是分组
IJobDetail job = JobBuilder.Create<HelloJob>().WithIdentity("任务1", "集合1").Build();
// 现在触发作业运行,然后每3秒重复执行一次HelloJob的Execute方法
ITrigger trigger = TriggerBuilder.Create().WithIdentity("触发器1", "集合1")
    .StartNow().WithSimpleSchedule(x =>
    x.WithIntervalInSeconds(3).RepeatForever()).Build();
// 使用触发器调度任务
await scheduler.ScheduleJob(job, trigger);
// 睡眠来显示正在发生的事情
await Task.Delay(TimeSpan.FromSeconds(900));
//关机
await scheduler.Shutdown();
Console.WriteLine("按任意键退出");
Console.ReadKey();
复制代码

5:启动调试

代码实现效果

 

 

 

 

 

 

posted on   Sleepy-Person  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5
点击右上角即可分享
微信分享提示