最近,在工作中遇到了 Quartz.net 这个组件,为了更好的理解项目代码的来龙去脉,于是决定好好的研究一下这个东西。确实是好东西,既然是好东西,我就拿出来分享一下。万丈高楼平地起,我们也从入门开始吧。

  欢迎使用 Quartz.NET 快速入门指南。 在阅读本指南时,必须注意以下条目:

  1、下载 Quartz.NET

           2、安装 Quartz.NET

           3、根据您自己的特定需求来配置 Quartz.Net

           4、展示一个示例应用程序

一、下载并安装

  您可以直接下载 ZIP 文件或使用 NuGet 包来获取文件。二者是有区别的,NuGet 包只包含运行 Quartz.NET 所必须的二进制文件,ZIP 文件就不一样了,包含源代码、示例和 Quartz.NET 服务器示例应用程序。

   Zip文件

  简短版本:如果你成功下载了 Quartz.NET 压缩包文件,只要将 ZIP 文件解压,从bin目录中获取 Quartz.dll 文件,就可以开始使用它了。

  Quartz.Net 的核心库是一个非常干净和独立的类库,不会强行依赖任何其他的二进制文件。 如果您想使用JSON.NET进行JSON序列化时,您可以根据需要选择加入更多的程序集。同时您只要保证在应用程序中包含了 Quartz.dll 文件就可以成功运行 Quartz.NET,也会和其他的二进制文件相处融洽。 因此,只要将 Quartz.dll 文件添加到使用它们的 Visual Studio 项目中就可以完美的运行。 您可以从路径bin \ your-target-framework-version \ release \ Quartz 中提取的文档中找到这些 dll。

二、NuGet包

  这是最简单的做法了,只需启动Visual Studio(安装了NuGet)并从包管理器扩展中添加对Quartz包的引用:

  1、右键单击项目的“引用”(References),然后选择“管理 NuGet 程序包(N)”(Manage NuGet Packages(N)) ...
           2、从左侧选择“浏览or在线”类别
           3、在左上方的搜索中输入 Quartz,然后按 回车 键
           4、从搜索结果中选择 Quartz.NET 并点击安装
           5、完成!

  或者使用NuGet的命令行来安装:

    Install-Package Quartz

  如果想要添加 JSON  序列化的功能,只需以相同的方式添加 Quartz.Serialization.Json 包就可以。

三、配置

  Quartz.NET 是一个支持灵活配置的库。Quartz.NET 提供三种的配置信息的方式(不相互排斥):

  1、以编程方式通过向调度程序工厂提供 NameValueCollection 参数

  2、通过使用 quartz-element 的标准 youapp.exe.config 配置文件(仅限完整的.NET框架)

  3、可以使用应用程序根目录中的  quartz.config 文件(适用于.NET Core和完整的.NET Framework)

  您可以在Quartz.NET zip文件中找到所有这些替代品的样本。

   Quartz Configuration Reference中提供了可用属性的完整文档。

  为了加速启动和运行,提供了最基本的配置信息的文件 quartz.config 看起来应该像这样:

    quartz.scheduler.instanceName = MyScheduler
quartz.jobStore.type = Quartz.Simpl.RAMJobStore,Quartz
quartz.threadPool.threadCount =

  请记住在 Visual Studio 的文件属性页上设置“复制到输出目录”以使值始终为“复制”。否则,配置文件就不会存在构建项目的目录中,就不会使用该配置文件。

  此配置创建的调度程序具有以下特征:

  quartz.scheduler.instanceName - 此调度程序的名称将为“MyScheduler”。
          quartz.threadPool.threadCount - 最多可同时运行3个作业。
          quartz.jobStore.type - 所有 Quartz 的数据,例如作业和触发器的详细信息,都保存在内存中(而不是数据库中)。即使你有一个数据库并希望在 Quartz 中使用它,我建议你在使用数据库打开一个全新的维度之前让 Quartz 使用 RamJobStore。

  实际上,如果你不想定义这些属性,Quartz.NET会提供合理的默认值

四、先看一个简单的示例程序

  现在您已经下载并安装了Quartz,现在是时候启动并运行一个示例应用程序了。 以下代码获取调度程序的实例,启动它,然后将其关闭:

     using System;
using System.Threading.Tasks; using Quartz;
using Quartz.Impl; namespace QuartzSampleApp
{
public class Program
{
private static void Main(string[] args)
{
// trigger async evaluation
RunProgram().GetAwaiter().GetResult();
} private static async Task RunProgram()
{
try
{
// 从Factory获取Scheduler实例
NameValueCollection props = new NameValueCollection
{
{ "quartz.serializer.type", "binary" }
};
StdSchedulerFactory factory = new StdSchedulerFactory(props);
IScheduler scheduler = await factory.GetScheduler(); // 并启动它
await scheduler.Start(); // some sleep to show what's happening
await Task.Delay(TimeSpan.FromSeconds()); // 当您准备关闭程序时,最后关闭调度程序
await scheduler.Shutdown();
}
catch (SchedulerException se)
{
await Console.Error.WriteLineAsync(se.ToString());
}
}
}
}

从Quartz 3.0开始,当在scheduler.Shutdown() 之后没有剩下的代码要执行时,你的应用程序将终止,因为没有任何活动的线程。 如果希望在处理Task.Delay和Shutdown之后调度程序继续运行,则应手动阻止退出应用程序。

现在运行该程序将不会显示任何内容。 10秒后,程序将终止。 让我们添加一些日志记录到控制台。

五、增加日志功能

LibLog可以配置为使用不同的日志框架; 即Log4Net,NLog和Serilog。

当LibLog没有检测到任何其他日志框架存在时,它将是不做任何事的。 如果您还没有一个设置好的日志框架,我们可以配置一个自定义的日志记录器提供程序,只需登录到控制台即可显示输出。

 LogProvider.SetCurrentLogProvider(new ConsoleLogProvider());

     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, string value)
{
throw new NotImplementedException();
}
}

六、探索使用 Job 作业的完整过程

现在,当我们启动应用程序时,我们应该获得更多信息。

    [::] [Info] Using object serializer: Quartz.Simpl.BinaryObjectSerializer, Quartz
[::] [Info] Initialized Scheduler Signaller of type: Quartz.Core.SchedulerSignalerImpl
[::] [Info] Quartz Scheduler v.3.0.7.0 created.
[::] [Info] RAMJobStore initialized.
[::] [Info] Scheduler meta-data: Quartz Scheduler (v3.0.7.) 'QuartzScheduler' with instanceId 'NON_CLUSTERED'
Scheduler class: 'Quartz.Core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed:
Using thread pool 'Quartz.Simpl.DefaultThreadPool' - with threads.
Using job-store 'Quartz.Simpl.RAMJobStore' - which does not support persistence. and is not clustered. [::] [Info] Quartz scheduler 'QuartzScheduler' initialized
[::] [Info] Quartz scheduler version: 3.0.7.0
[::] [Info] Scheduler QuartzScheduler_$_NON_CLUSTERED started.

我们需要一个简单的测试工作来测试功能,让我们创建HelloJob来向控制台输出问候语。

     public sealed class HelloJob : IJob
{
public async Task Execute(IJobExecutionContext context)
{
await Console.Out.WriteLineAsync("Greetings from HelloJob!");
}
}

要做一些有趣的事情,您需要在Task.Delay之前的Start() 方法之后使用代码。

     // 定义job作业并将其绑定到HelloJob类
IJobDetail job = JobBuilder.Create<HelloJob>()
.WithIdentity("job1", "group1")
.Build(); //触发作业立即运行,然后每10秒重复一次
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInSeconds()
.RepeatForever())
.Build(); //告诉 quartz 使用我们的触发器安排作业
await scheduler.ScheduleJob(job, trigger);

完整的控制台应用程序现在看起来像这样

     using System;
using System.Threading.Tasks; using Quartz;
using Quartz.Impl;
using Quartz.Logging; namespace QuartzSampleApp
{
public class Program
{
private static void Main(string[] args)
{
LogProvider.SetCurrentLogProvider(new ConsoleLogProvider()); RunProgram().GetAwaiter().GetResult(); Console.WriteLine("Press any key to close the application");
Console.ReadKey();
} private static async Task RunProgram()
{
try
{
// Grab the Scheduler instance from the Factory
NameValueCollection props = new NameValueCollection
{
{ "quartz.serializer.type", "binary" }
};
StdSchedulerFactory factory = new StdSchedulerFactory(props);
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()
.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()); // and last shut down the scheduler when you are ready to close your program
await scheduler.Shutdown();
}
catch (SchedulerException se)
{
Console.WriteLine(se);
}
} // 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, string value)
{
throw new NotImplementedException();
}
}
} public class HelloJob : IJob
{
public async Task Execute(IJobExecutionContext context)
{
await Console.Out.WriteLineAsync("Greetings from HelloJob!");
}
}
}

现在去探索Quartz.NET吧! 您可以继续阅读本教程。原文地址如下:https://www.quartz-scheduler.net/documentation/quartz-3.x/quick-start.html

Quartz.NET快速入门指南的更多相关文章

  1. AngularJS快速入门指南20:快速参考

    thead>tr>th, table.reference>tbody>tr>th, table.reference>tfoot>tr>th, table ...

  2. AngularJS快速入门指南19:示例代码

    本文给出的大部分示例都可以直接运行,通过点击运行按钮来查看结果,同时支持在线编辑代码. <div ng-app=""> <p>Name: <input ...

  3. AngularJS快速入门指南18:Application

    是时候创建一个真正的AngularJS单页面应用程序了(SPA). 一个AngularJS应用程序示例 你已经了解了足够多的内容来创建第一个AngularJS应用程序: My Note Save Cl ...

  4. AngularJS快速入门指南17:Includes

    使用AngularJS,你可以在HTML中包含其它的HTML文件. 在HTML中包含其它HTML文件? 当前的HTML文档还不支持该功能.不过W3C建议在后续的HTML版本中增加HTML import ...

  5. AngularJS快速入门指南16:Bootstrap

    thead>tr>th, table.reference>tbody>tr>th, table.reference>tfoot>tr>th, table ...

  6. AngularJS快速入门指南15:API

    thead>tr>th, table.reference>tbody>tr>th, table.reference>tfoot>tr>th, table ...

  7. AngularJS快速入门指南14:数据验证

    thead>tr>th, table.reference>tbody>tr>th, table.reference>tfoot>tr>th, table ...

  8. AngularJS快速入门指南13:表单

    一个AngularJS表单是一组输入型控件的集合. HTML控件 HTML输入型标签标包括: input标签 select标签 button标签 textarea标签 HTML表单 HTML表单将各种 ...

  9. AngularJS快速入门指南12:模块

    AngularJS模块定义了一个application. 模块是一个application中不同部分的容器. application中的所有控制器都应该属于一个模块. 带有一个控制器的模块 下面这个a ...

随机推荐

  1. [JAVA]JAVA多线程实现方法之——实现Runnable接口

    public class MultiThread { public static void main(String[] args) { Thread t1 = new Thread(new Threa ...

  2. docker的ubuntu镜像无ifconfig和ping netstat命令

    docker的ubuntu镜像无ifconfig和ping命令 或者 ubuntu系统中无ifconfig 和 ping 解决方案: 执行以下鸣冷: apt-get update apt-get in ...

  3. 关于音频总线IIS的学习---Verilog

    关于音频总线IIS的学习---Verilog 主要思想: 在分析寄存器的值变化的时候,将时钟的边沿分两边来看,边沿之前,边沿之后,在always 块语句里面用来分析判断的寄存器的值,都应该用边沿变化之 ...

  4. Pod配置PersistentVolumeClaim详解

    1,创建PersistentVolume kind: PersistentVolume apiVersion: v1 metadata: name: task-pv-volume labels: ty ...

  5. [转]Java事件处理机制- 事件监听器的四种实现方式

    原文来自http://stefan321.iteye.com/blog/345221 自身类作为事件监听器 外部类作为事件监听器 匿名内部类作为事件监听器 内部类作为事件监听器 自身类作为事件监听器: ...

  6. [UE4]Wrap Box流布局

    一.Wrap Box的子控件可以根据Wrap Box的大小自动换行 1.Wrap Box.Inner Slot Padding:Wrap Box所有子控件留白,可以实现每个控件之间的间距都是相同,但是 ...

  7. ubuntu下的Nessus插件更新

    00x1: 记录下nessus插件离线更新,免得每次度娘我Nessus是放在虚拟机里面. 00x2: nessus 插件更新地址: https://plugins.nessus.org/v2/offl ...

  8. 02-Introspector内省设置单个属性

    package com.oa.test; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; ...

  9. 第二章 FFmpeg常用命令

    2.1 FFmpeg常见的命令大概分为6个部分 ffmpeg信息查询部分 公共操作参数部分 文件主要操作参数部分 视频操作参数部分 字幕操作参数部分 2.1.1 FFmpeg的封装转换 FFmpeg ...

  10. "Native table 'performance_schema'.'session_variables' has the wrong structure") [SQL: "SHOW VARIABLES LIKE 'sql_mode'"]

    mysql_upgrade -u root -p--force 升级完重启