Quartz是一个完全由JAVA编写的开源作业调度框架。

Quartz.NET是Quartz的.NET移植,它用C#写成,可用于.Net以及.Net Core的应用中。

目前最新的quartz.net版本3.0.6 只支持.netframework4.5.2及.netstandard2.0及以上版本

官方实例:https://www.quartz-scheduler.net/documentation/quartz-3.x/quick-start.html

  1. using Quartz;
  2. using Quartz.Impl;
  3. using Quartz.Logging;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Collections.Specialized;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10.  
  11. namespace Demo
  12. {
  13. class Program
  14. {
  15. private static void Main(string[] args)
  16. {
  17. LogProvider.SetCurrentLogProvider(new ConsoleLogProvider());
  18.  
  19. RunProgramRunExample().GetAwaiter().GetResult();
  20.  
  21. Console.WriteLine("Press any key to close the application");
  22. Console.ReadKey();
  23. }
  24.  
  25. private static async Task RunProgramRunExample()
  26. {
  27. try
  28. {
  29. // Grab the Scheduler instance from the Factory
  30. NameValueCollection props = new NameValueCollection
  31. {
  32. { "quartz.serializer.type", "binary" }
  33. };
  34. StdSchedulerFactory factory = new StdSchedulerFactory(props);
  35. IScheduler scheduler = await factory.GetScheduler();
  36.  
  37. // and start it off
  38. await scheduler.Start();
  39.  
  40. // define the job and tie it to our HelloJob class
  41. IJobDetail job = JobBuilder.Create<HelloJob>()
  42. .WithIdentity("job1", "group1")
  43. .Build();
  44.  
  45. // Trigger the job to run now, and then repeat every 10 seconds
  46. ITrigger trigger = TriggerBuilder.Create()
  47. .WithIdentity("trigger1", "group1")
  48. .StartNow()
  49. .WithSimpleSchedule(x => x
  50. .WithIntervalInSeconds()
  51. .RepeatForever())
  52. .Build();
  53.  
  54. // Tell quartz to schedule the job using our trigger
  55. await scheduler.ScheduleJob(job, trigger);
  56.  
  57. // some sleep to show what's happening
  58. await Task.Delay(TimeSpan.FromSeconds());
  59.  
  60. // and last shut down the scheduler when you are ready to close your program
  61. await scheduler.Shutdown();
  62. }
  63. catch (SchedulerException se)
  64. {
  65. Console.WriteLine(se);
  66. }
  67. }
  68.  
  69. // simple log provider to get something to the console
  70. private class ConsoleLogProvider : ILogProvider
  71. {
  72. public Logger GetLogger(string name)
  73. {
  74. Logger loger = LoggerMethod;
  75. return loger;
  76.  
  77. return (level, func, exception, parameters) =>
  78. {
  79. if (level >= LogLevel.Info && func != null)
  80. {
  81. Console.WriteLine("[" + DateTime.Now.ToLongTimeString() + "] [" + level + "] " + func(), parameters);
  82. }
  83. return true;
  84. };
  85. }
  86.  
  87. private bool LoggerMethod(LogLevel logLevel, Func<string> messageFunc, Exception exception = null, params object[] formatParameters)
  88. {
  89. if (logLevel >= LogLevel.Info && messageFunc != null)
  90. {
  91. Console.WriteLine("[" + DateTime.Now.ToLongTimeString() + "] [" + logLevel + "] " + messageFunc(), formatParameters);
  92. }
  93. return true;
  94. }
  95.  
  96. public IDisposable OpenNestedContext(string message)
  97. {
  98. throw new NotImplementedException();
  99. }
  100.  
  101. public IDisposable OpenMappedContext(string key, string value)
  102. {
  103. throw new NotImplementedException();
  104. }
  105. }
  106. }
  107.  
  108. public class HelloJob : IJob
  109. {
  110. public async Task Execute(IJobExecutionContext context)
  111. {
  112. await Console.Out.WriteLineAsync("Greetings from HelloJob!");
  113. }
  114. }
  115.  
  116. }

看了这个官方的示例,你会发现QuarztNet3.0版本较之2.0版本,引入了async/await

下面记录一下学习过程:

一、使用VS2013新建Winform项目,.Net版本为4.5.2,通过Nuget命令行获取Quarzt.Net:Install-Package Quartz. 如果你在安装过程中报错,那么,要注意你的.Net版本

二、万事俱备,开始编码

多任务,一个每分钟的第30秒播放音频,一个每分钟的第0秒写文本文件

  1. private async void PlaySound()
  2. {
  3. //1.通过工厂获取一个调度器的实例
  4. StdSchedulerFactory factory = new StdSchedulerFactory();
  5. _scheduler = await factory.GetScheduler();
  6. await _scheduler.Start();
  7.  
  8. //创建任务对象
  9. IJobDetail job = JobBuilder.Create<SoundJob>()
  10. .WithIdentity("job1", "group1")
  11. .Build();
  12.  
  13. //创建触发器
  14. ITrigger trigger = TriggerBuilder.Create()
  15. .WithIdentity("trigger1", "group1")
  16. .StartNow()
  17. .WithCronSchedule("30 0/1 * * * ?")//每分钟的第30秒执行
  18. .Build();
  19.  
  20. //将任务加入到任务池
  21. await _scheduler.ScheduleJob(job, trigger);
  22.  
  23. job = JobBuilder.Create<PrintJob>()
  24. .WithIdentity("job2", "group1")
  25. .Build();
  26.  
  27. trigger = TriggerBuilder.Create()
  28. .WithIdentity("trigger2", "group1")
  29. .StartNow()
  30. .WithCronSchedule("0 0/1 * * * ?")//每分钟的第0秒执行
  31. .Build();
  32.  
  33. await _scheduler.ScheduleJob(job, trigger);
  34. }
  1. public class PrintJob : IJob
  2. {
  3. string fileName = "printlog.txt";
  4. public Task Execute(IJobExecutionContext context)
  5. {
  6. StreamWriter writer = new StreamWriter(fileName, true);
  7. Task task = writer.WriteLineAsync(string.Format("{0}", DateTime.Now.ToLongTimeString()));
  8. writer.Close();
  9. writer.Dispose();
  10. return task;
  11. }
  12. }
  1. public class SoundJob : IJob
  2. {
  3. public static Action<string> _printLogCallBack;
  4.  
  5. public string Sound { get; set; }
  6.  
  7. public Task Execute(IJobExecutionContext context)
  8. {
  9. JobDataMap jobDataMap = context.JobDetail.JobDataMap;
  10. string sound = jobDataMap.GetString("sound");
  11. int number = jobDataMap.GetInt("number");
  12.  
  13. if (_printLogCallBack != null)
  14. { _printLogCallBack(string.Format("{0}[{1}] 执行任务 Sound {2}", Environment.NewLine, DateTime.Now.ToLongTimeString(), Sound)); }
  15.  
  16. return Task.Factory.StartNew(() =>
  17. {
  18. SoundPlayer player = new SoundPlayer();
  19. player.SoundLocation = @"F:\FFOutput\421204264234974-.wav";
  20. player.Load();
  21. player.Play();
  22. });
  23. }
  24. }

以上是主要部分,另外还涉及到日志部分,日志我是直接输出到UI上,我们可以看到以下编码的区别,ConsoleLogProvider中输出的日志可以直接打印,而SoundJob中的却不可以,说明SoundJob中的方法是异步执行的,需要解决跨线程访问UI控件的问题,我们可以使用UI线程的上下文对象SynchronizationContext _syncContext,将输出日志的方法,委托给UI线程执行。

  1. private void Form1_Load(object sender, EventArgs e)
  2. {
  3. ConsoleLogProvider logProvider = new ConsoleLogProvider();
  4. logProvider.SetLogCallBack((log) =>
  5. {
  6. this.rchMessage.AppendText(log);
  7. });
  8.  
  9. SoundJob._printLogCallBack = (log) =>
  10. {
  11. _syncContext.Send((obj) =>
  12. {
  13. this.rchMessage.AppendText(log.ToString());
  14. }, null);
  15. };
  16.  
  17. LogProvider.SetCurrentLogProvider(logProvider);
  18. }

关于Cron表达式:

  1. /*
  2. 由7段构成:秒 分 时 日 月 星期 年(可选)
  3.  
  4. "-" :表示范围 MON-WED表示星期一到星期三
  5. "," :表示列举 MON,WEB表示星期一和星期三
  6. "*" :表是“每”,每月,每天,每周,每年等
  7. "/" :表示增量:0/15(处于分钟段里面) 每15分钟,在0分以后开始,3/20 每20分钟,从3分钟以后开始
  8. "?" :只能出现在日,星期段里面,表示不指定具体的值
  9. "L" :只能出现在日,星期段里面,是Last的缩写,一个月的最后一天,一个星期的最后一天(星期六)
  10. "W" :表示工作日,距离给定值最近的工作日
  11. "#" :表示一个月的第几个星期几,例如:"6#3"表示每个月的第三个星期五(1=SUN...6=FRI,7=SAT)
  12.  
  13. 如果Minutes的数值是 '0/15' ,表示从0开始每15分钟执行
  14.  
  15. 如果Minutes的数值是 '3/20' ,表示从3开始每20分钟执行,也就是‘3/23/43’
  16. */

运行效果图:

QuartzNet3.0实现作业调度的更多相关文章

  1. ZAM 3D 制作简单的3D字幕 流程(二)

    原地址:http://www.cnblogs.com/yk250/p/5663907.html 文中表述仅为本人理解,若有偏差和错误请指正! 接着 ZAM 3D 制作简单的3D字幕 流程(一) .本篇 ...

  2. ZAM 3D 制作3D动画字幕 用于Xaml导出

    原地址-> http://www.cnblogs.com/yk250/p/5662788.html 介绍:对经常使用Blend做动画的人来说,ZAM 3D 也很好上手,专业制作3D素材的XAML ...

  3. 微信小程序省市区选择器对接数据库

    前言,小程序本身是带有地区选着器的(网站:https://mp.weixin.qq.com/debug/wxadoc/dev/component/picker.html),由于自己开发的程序的数据是很 ...

  4. osg编译日志

    1>------ 已启动全部重新生成: 项目: ZERO_CHECK, 配置: Debug x64 ------1> Checking Build System1> CMake do ...

  5. 作业调度框架 Quartz.NET 2.0 StepByStep

    注:目前网上诸多介绍Quartz.net的文章,甚至Quartz.net官网上的Tutorial都是1.0版本的,而这个项目在2.0版本对项目进行了比较大规模的修改,使得原有的很多例子都不能运行,故写 ...

  6. Quartz.NET 2.0 作业调度框架使用

    Quartz.NET是一个开源的作业调度框架,是 OpenSymphony 的 Quartz API 的.NET移植,它用C#写成,可用于winform和asp.net应用中.它提供了巨大的灵活性而不 ...

  7. Quartz.NET实现作业调度(3.0版本实现)定时执行一个任务

    2.0版本请参考https://www.cnblogs.com/best/p/7658573.html这里的文章很详细: 我们现在想每5秒钟往txt文件夹里存储一个时间 首先:定义一个类,实现Quar ...

  8. Asp.Net Core2.0 基于QuartzNet任务管理系统

    Quartz.NET官网地址:https://www.quartz-scheduler.net/ Quartz.NET文档地址:https://www.quartz-scheduler.net/doc ...

  9. Spark核心作业调度和任务调度之DAGScheduler源码

    前言:本文是我学习Spark 源码与内部原理用,同时也希望能给新手一些帮助,入道不深,如有遗漏或错误的,请在原文评论或者发送至我的邮箱 tongzhenguotongzhenguo@gmail.com ...

随机推荐

  1. 批量删除进程清理 minerd

    发现顽固minerd 进程与ntp一起启动,所以一起杀掉 yum remove ntp kill -9 `ps -ef | grep ntp|awk '{print $2}'` kill -9 `ps ...

  2. asp.net 关于Response.Redirect重定向前无法弹出alert对话框的问题

    要实现的功能:某项操作后,使用alert()提示框提示"操作成功"之类的提示,然后使用response.Redirect()来进行页面重定向. 出现的问题:运行代码,操作完成后,直 ...

  3. TZOJ 2755 国际象棋(广搜+哈希)

    描述 在n*n的国际象棋棋盘中,给定一“马(Knight)”和一“后(Queen)”的位置,问“马”能否在m步之内(包括m步)到达“后”的位置?马的走法是:每步棋先横走或直走一格,然后再斜走一格,即走 ...

  4. 查看端口号根据pid号找到相关占用端口应用

    查看端口号根据pid号找到相关占用端口应用   8080 端口被占用不知道被哪个应用软件占用,下面我来教你查出那个该死的应用 方法/步骤   1 首先用netstat 找到端口对应的pid号,找到之后 ...

  5. access数据库收缩(压缩)

    一般是因为表中有大量没用的数据,把没用的数据全部删除 菜单栏的“工具”——“数据库实用工具”——“压缩和修复数据库” OK啦

  6. iOS - xcode - label 字体自动根据宽高 显示完全

    1. label 左右约束要给.  2.代码实现label.adjustsFontSizeToFitWidth = YES

  7. 坑爹的HP

    昨天晚上帮人远程修理电脑,情况是这样的: HP CQ45笔记本, 比较老的机器, win32 xp sp3 系统, 突然发现没有声音了,而且右下角也没有出现小喇叭图标. 处理过程: 1.先查看了控制面 ...

  8. Docker commit 制作weblogic镜像

    第一:前提条件 1.本机必须已经安装了docker 容器 2.pull 一个基础的镜像  如图:rastasheep/ubuntu-sshd 第二:利用docker commit  命令 将容器的状态 ...

  9. Django之ORM数据库

    5.1 数据库的配置 1    django默认支持sqlite,mysql, oracle,postgresql数据库.  <1> sqlite django默认使用sqlite的数据库 ...

  10. Laravel + Vue 之 OPTIONS 请求的处理

    问题: 在 Vue 对后台的请求中,一般采用 axios 对后台进行 Ajax 交互. 交互发生时,axios 一般会发起两次请求,一次为 Options 试探请求,一次为正式请求. 由此带来的问题是 ...