Quartz.NET 实现定时任务调度
Quartz.NET Quick Start Guide
Welcome to the Quick Start Guide for Quartz.NET. As you read this guide, expect to see details of:
- Downloading Quartz.NET
- Installing Quartz.NET
- Configuring Quartz to your own particular needs
- Starting a sample application
Download and Install
You can either download the zip file or use the NuGet package. NuGet package contains only the binaries needed to run Quartz.NET, zip file comes with source code, samples and Quartz.NET server sample application.
Zip Archive
Short version: Once you’ve downloaded Quartz.NET, unzip it somewhere, grab the Quartz.dll from bin directory and start to use it.
Quartz core library does not have any hard binary dependencies. You can opt-in to more dependencies when you choose to use JSON serialization package, which requires JSON.NET. You need to have at least Quartz.dll beside your app binaries to successfully run Quartz.NET. So just add it as a references to your Visual Studio project that uses them. You can find these dlls from extracted archive from path bin\your-target-framework-version\release\Quartz.
NuGet Package
Couldn’t get any simpler than this. Just fire up Visual Studio (with NuGet installed) and add reference to package Quartz from package manager extension:
- Right-click on your project’s References and choose Manage NuGet Packages…
- Choose Online category from the left
- Enter Quartz to the top right search and hit enter
- Choose Quartz.NET from search results and hit install
- Done!
or from NuGet Command-Line:
Install-Package Quartz
If you want to add JSON Serialization, just add the Quartz.Serialization.Json package the same way.
Configuration
This is the big bit! Quartz.NET is a very configurable library. There are three ways (which are not mutually exclusive) to supply Quartz.NET configuration information:
- Programmatically via providing NameValueCollection parameter to scheduler factory
- Via standard youapp.exe.config configuration file using quartz-element (full .NET framework only)
- quartz.config file in your application’s root directory (works both with .NET Core and full .NET Framework)
You can find samples of all these alternatives in the Quartz.NET zip file.
Full documentation of available properties is available in the Quartz Configuration Reference.
To get up and running quickly, a basic quartz.config looks something like this:
quartz.scheduler.instanceName = MyScheduler
quartz.jobStore.type = Quartz.Simpl.RAMJobStore, Quartz
quartz.threadPool.threadCount = 3
Remember to set the Copy to Output Directory on Visual Studio’s file property pages to have value Copy always. Otherwise the config will not be seen if it’s not in build directory.
The scheduler created by this configuration has the following characteristics:
- quartz.scheduler.instanceName - This scheduler’s name will be “MyScheduler”.
- quartz.threadPool.threadCount - Maximum of 3 jobs can be run simultaneously.
- quartz.jobStore.type - All of Quartz’s data, such as details of jobs and triggers, is held in memory (rather than in a database). Even if you have a database and want to use it with Quartz, I suggest you get Quartz working with the RamJobStore before you open up a whole new dimension by working with a database.
Actually you don’t need to define these properties if you don’t want to, Quartz.NET comes with sane defaults
Starting a Sample Application
Now you’ve downloaded and installed Quartz, it’s time to get a sample application up and running. The following code obtains an instance of the scheduler, starts it, then shuts it down:
Program.cs
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
{
// 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();
// 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();
}
catch (SchedulerException se)
{
await Console.Error.WriteLineAsync(se.ToString());
}
}
}
}
Once you obtain a scheduler using StdSchedulerFactory.GetDefaultScheduler(), your application will not terminate by default until you call scheduler.Shutdown(), because there will be active threads (non-daemon threads).
No running the program will not show anything. When 10 seconds have passed the program will just terminate. Lets add some logging to console.
Adding logging
LibLog can be configured to use different logging frameworks under the hood; namely Log4Net, NLog and Serilog.
When LibLog does not detect any other logging framework to be present, it will be silent. We can configure a custom logger provider that just logs to console show the output if you don’t have logging framework setup ready yet.
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();
}
}
Trying out the application and adding jobs
No we should get a lot more information when we start the application.
[12.51.10] [Info] Quartz.NET properties loaded from configuration file 'C:\QuartzSampleApp\quartz.config'
[12.51.10] [Info] Initialized Scheduler Signaller of type: Quartz.Core.SchedulerSignalerImpl
[12.51.10] [Info] Quartz Scheduler v.0.0.0.0 created.
[12.51.10] [Info] RAMJobStore initialized.
[12.51.10] [Info] Scheduler meta-data: Quartz Scheduler (v0.0.0.0) 'MyScheduler' with instanceId 'NON_CLUSTERED'
Scheduler class: 'Quartz.Core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
Using thread pool 'Quartz.Simpl.DefaultThreadPool' - with 3 threads.
Using job-store 'Quartz.Simpl.RAMJobStore' - which does not support persistence. and is not clustered.
[12.51.10] [Info] Quartz scheduler 'MyScheduler' initialized
[12.51.10] [Info] Quartz scheduler version: 0.0.0.0
[12.51.10] [Info] Scheduler MyScheduler_$_NON_CLUSTERED started.
We need a simple test job to test the functionality, lets create HelloJob that outputs greetings to console.
public class HelloJob : IJob
{
public Task Execute(IJobExecutionContext context)
{
await Console.Out.WriteLineAsync("Greetings from HelloJob!");
}
}
To do something interesting, you need code just after Start() method, before the Task.Delay.
// 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);
The complete console application will now look like this
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());
RunProgramRunExample().GetAwaiter().GetResult();
Console.WriteLine("Press any key to close the application");
Console.ReadKey();
}
private static async Task RunProgramRunExample()
{
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(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();
}
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!");
}
}
}
Now go have some fun exploring Quartz.NET! You can continue by reading the tutorial.
Quartz.NET 实现定时任务调度的更多相关文章
- Spring和Quartz整合实现定时任务调度
在Spring中可以很方便的使用Quartz来实现定时任务等功能,Quartz主要就是Schedule(任务调度器),Job(作业任务)和Trigger(触发器)三者的关系. 实现方式有多种,在此就介 ...
- Quartz.Net实现定时任务调度
Quartz.Net介绍: Quartz一个开源的作业调度框架,OpenSymphony的开源项目.Quartz.Net 是Quartz的C#移植版本. 它一些很好的特性: 1:支持集群,作业分组,作 ...
- 一文揭秘定时任务调度框架quartz
之前写过quartz或者引用过quartz的一些文章,有很多人给我发消息问quartz的相关问题, quartz 报错:java.lang.classNotFoundException quartz源 ...
- 项目一:第十四天 1.在realm中动态授权 2.Shiro整合ehcache 缓存realm中授权信息 3.动态展示菜单数据 4.Quartz定时任务调度框架—Spring整合javamail发送邮件 5.基于poi实现分区导出
1 Shiro整合ehCache缓存授权信息 当需要进行权限校验时候:四种方式url拦截.注解.页面标签.代码级别,当需要验证权限会调用realm中的授权方法 Shiro框架内部整合好缓存管理器, ...
- Hosted Services+Quartz实现定时任务调度
背景 之前.net core使用quartz.net时,总感觉非常变扭,百度和谷歌了N久都没解决以下问题,造成代码丑陋,非常不优雅: 1.项目启动时,要立刻恢复执行quartz.net中的任务 2.q ...
- Window服务基于Quartz.Net组件实现定时任务调度(二)
前言: 在上一章中,我们通过利用控制台实现定时任务调度,已经大致了解了如何基于Quartz.Net组件实现任务,至少包括三部分:job(作业),trigger(触发器),scheduler(调度器). ...
- C#/.NET/.NET Core定时任务调度的方法或者组件有哪些--Timer,FluentScheduler,TaskScheduler,Gofer.NET,Coravel,Quartz.NET还是Hangfire?
原文由Rector首发于 码友网 之 <C#/.NET/.NET Core应用程序编程中实现定时任务调度的方法或者组件有哪些,Timer,FluentScheduler,TaskSchedule ...
- quartz 定时任务调度管理器
本项目使用的是spring-quartz 以下配置可以开启多个已知定时任务 <?xml version="1.0" encoding="UTF-8"?&g ...
- [源码分析] 定时任务调度框架 Quartz 之 故障切换
[源码分析] 定时任务调度框架 Quartz 之 故障切换 目录 [源码分析] 定时任务调度框架 Quartz 之 故障切换 0x00 摘要 0x01 基础概念 1.1 分布式 1.1.1 功能方面 ...
随机推荐
- 【递推】【推导】【乘法逆元】UVA - 11174 - Stand in a Line
http://blog.csdn.net/u011915301/article/details/43883039 依旧是<训练指南>上的一道例题.书上讲的比较抽象,下面就把解法具体一下.因 ...
- 【推导】Codeforces Round #411 (Div. 1) B. Minimum number of steps
最后肯定是bbbb...aaaa...这样. 你每进行一系列替换操作,相当于把一个a移动到右侧. 会增加一些b的数量……然后你统计一下就行.式子很简单. 喵喵喵,我分段统计的,用了等比数列……感觉智障 ...
- GIL,queue,进程池与线程池
GIL 1.什么是GIL(这是Cpython解释器) GIL本质就是一把互斥锁,既然是互斥锁,原理都是一样的,都是让多个并发线程同一时间只能有一个执行 即:有了GIL的存在,同一进程内的多个线程同一时 ...
- SourceTree运行慢的解决方案
以下两个Git命令可以解决SourceTree运行慢: git gc git prune 可以在SourceTree点击命令行模式打开Git命令行窗口输入,等待片刻执行完成,SourceTree的运行 ...
- PHP登录(连接数据库)小案例
实现效果 数据库信息 代码示例: 1. login.php <!DOCTYPE html> <html> <head> <met ...
- rocketmq,zookeeper,redis分别持久化的方式
1.rocketmq持久化: RocketMQ 的所有消息都是持久化的, 先写入系统 PAGECACHE, 然后刷盘, 可以保证内存与磁盘都有一份数据,访问时,直接从内存读取. RocketMQ 的所 ...
- express默认配置文件app.js
Express路由 Express模块化路由 Express中间件 Express结合jade模板渲染HTML 看完上面的,再回头看这app.js,就应该感觉没什么压力了,主要包含http的创建,基本 ...
- C#读取Windows日志
管理-->事件查看器 可以查看[应用程序].[安全].[系统]等分类的日志 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 2 ...
- 工作中常用Lixu命令学习笔记
对于Linux,我是菜鸟,也是在工作中了才开始慢慢接触,用Linux的人都我都会觉得屌屌的,现在把工作中常用的一些Linux命令记录一下,供以后学习和参考. cd 这可能是我觉得Linux最简单的一个 ...
- PTCSolution 关注
2013.12.28更新: 经过几次整理和再次租赁下线,点击数明显增加,现在995下线点击数3413.再将2页半的点击数低的下线替换掉,AVG肯定超过4. 这么短的时间整理效果如此明显是我没有想到 ...