Quartz.NET - Quartz.NET Quick Start Guide

转自:http://www.quartz-scheduler.net/documentation/quartz-2.x/quick-start.html

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 and Common.Logging.dll from bin directory and start to use them.

Quartz depends only on single third-party library called Common.Logging (which contains logging abstractions that allow you to use the logging provider that suites you the best). You need to have Quartz.dll and Commong.Logging.dll beside your app binaries to successfully run Quartz.NET. So just add them as 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 packageQuartz 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

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
  • quartz.config file in your application‘s root directory

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.threadPool.threadCount = 3
quartz.jobStore.type = Quartz.Simpl.RAMJobStore, Quartz

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 - There are 3 threads in the thread pool, which means that a 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;

using Quartz;
using Quartz.Impl;

namespace ConsoleApplication1
{
    public class Program
    {
        private static void Main(string[] args)
        {
            try
            {
                // Grab the Scheduler instance from the Factory
                IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();

                // and start it off
                scheduler.Start();

                // some sleep to show what‘s happening
                Thread.Sleep(TimeSpan.FromSeconds(60));

                // and last shut down the scheduler when you are ready to close your program
                scheduler.Shutdown();
            }
            catch (SchedulerException se)
            {
                Console.WriteLine(se);
            }
        }
    }
}

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

Common.Logging can be configured to use different logging frameworks under the hood; namely Enterprise Library, Log4Net and NLog.

However, to keep things simple for our example we take the simple route and configure logging using code to just log to the console using Common.Logging basic logging mechanism.

Add the following line to the beginning of your Program.cs

Common.Logging.LogManager.Adapter = new Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter { Level = Common.Logging.LogLevel.Info};

Trying out the application and adding jobs

No we should get a lot more information when we start the application.

11.1.2014 14:52:04 [INFO]  Quartz.Impl.StdSchedulerFactory - Quartz.NET properties loaded from configuration file ‘c:\ConsoleApplication1\bin\Debug\quartz.config‘
11.1.2014 14:52:04 [INFO]  Quartz.Impl.StdSchedulerFactory - Using default implementation for object serializer
11.1.2014 14:52:04 [INFO]  Quartz.Impl.StdSchedulerFactory - Using default implementation for ThreadExecutor
11.1.2014 14:52:04 [INFO]  Quartz.Core.SchedulerSignalerImpl - Initialized Scheduler Signaller of type: Quartz.Core.SchedulerSignalerImpl
11.1.2014 14:52:04 [INFO]  Quartz.Core.QuartzScheduler - Quartz Scheduler v.2.2.1.400 created.
11.1.2014 14:52:04 [INFO]  Quartz.Simpl.RAMJobStore - RAMJobStore initialized.
11.1.2014 14:52:04 [INFO]  Quartz.Core.QuartzScheduler - Scheduler meta-data: Quartz Scheduler (v2.2.1.400) ‘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.SimpleThreadPool‘ - with 3 threads.
  Using job-store ‘Quartz.Simpl.RAMJobStore‘ - which does not support persistence. and is not clustered.

11.1.2014 14:52:04 [INFO]  Quartz.Impl.StdSchedulerFactory - Quartz scheduler ‘MyScheduler‘ initialized
11.1.2014 14:52:04 [INFO]  Quartz.Impl.StdSchedulerFactory - Quartz scheduler version: 2.2.1.400
11.1.2014 14:52:04 [INFO]  Quartz.Core.QuartzScheduler - 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 void Execute(IJobExecutionContext context)
    {
        Console.WriteLine("Greetings from HelloJob!");
    }
}

To do something interesting, you need code just after Start() method, before the Thread.Sleep.

// 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
scheduler.ScheduleJob(job, trigger);

The complete console application will now look like this

using System;
using System.Threading;

using Quartz;
using Quartz.Impl;
using Quartz.Job;

namespace ConsoleApplication1
{
    public class Program
    {
        private static void Main(string[] args)
        {
            try
            {
                Common.Logging.LogManager.Adapter = new Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter {Level = Common.Logging.LogLevel.Info};

                // Grab the Scheduler instance from the Factory
                IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();

                // and start it off
                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
                scheduler.ScheduleJob(job, trigger);

                // some sleep to show what‘s happening
                Thread.Sleep(TimeSpan.FromSeconds(60));

                // and last shut down the scheduler when you are ready to close your program
                scheduler.Shutdown();
            }
            catch (SchedulerException se)
            {
                Console.WriteLine(se);
            }

            Console.WriteLine("Press any key to close the application");
            Console.ReadKey();
        }
    }

    public class HelloJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            Console.WriteLine("Greetings from HelloJob!");
        }
    }
}

Now go have some fun exploring Quartz.NET! You can continue by reading the tutorial.

时间: 2024-10-16 22:31:38

Quartz.NET - Quartz.NET Quick Start Guide的相关文章

Quartz Quick Start Guide

Welcome to the QuickStart guide for Quartz. As you read this guide, expect to see details of: Downloading Quartz Installing Quartz Configuring Quartz to your own particular needs Starting a sample application Download and Installation of Quartz To do

[摘录]quarts:Quartz Quick Start Guide

(Primarily authored by Dafydd James) Welcome to the QuickStart guide for Quartz. As you read this guide, expect to see details of: Downloading Quartz Installing Quartz Configuring Quartz to your own particular needs Starting a sample application Down

【Quartz】Quartz的搭建、应用(单独使用Quartz)

阅读目录 > 参考的优秀资料 > 版本说明 > 简单的搭建 > 在Web应用中使用Quartz > 常用的Cron Schedule Quartz在Java构建的系统中,是十分常用的定时任务框架. 本文,记录.介绍Quartz的简单入门的单独搭建(此文入门学习Quartz为主,并非基于Spring托管形式). > 参考的优秀资料 Quartz Quick Start Guide Chapter 3: Logback configuration > 版本说明 除了Q

【Quartz】Quartz的简单搭建

Quartz在Java构建的系统中,是十分常用的定时任务框架. 本文,记录.介绍Quartz的简单入门的单独搭建(此文入门学习Quartz为主,并非基于Spring托管形式). > 参考的优秀资料 Quartz Quick Start Guide Chapter 3: Logback configuration > 版本说明 除了Quartz,还引入logback(为了看详细的日志嘛!) <dependencies> <dependency> <groupId&g

Chapter 0.SymmetricDS快速入门指南( Quick Start Guide)

本文档是SymmetricDS3.6.14文档的第一章节Quick Start Guide文档的翻译,的目的是帮助读者快速搭建一个SymmetricDS集群并普及一些基本概念术语. 本文档描述了如何在两个SymmetricDS节点之间同步两个相同schema的数据库.下面的例子构建了一个分销业务模型,有一个中央数据库(我们叫它root或者corp节点)和多个零售商店的数据库(我们叫它client或者store节点).对于本教程,我们将只有一个store(商店)节点,如下图.如果你愿意,可以再教程

Akka Stream文档翻译:Quick Start Guide: Reactive Tweets

Quick Start Guide: Reactive Tweets 快速入门指南: Reactive Tweets (reactive tweets 大概可以理解为“响应式推文”,在此可以测试下GFW是否还在正常工作 Twitter) A typical use case for stream processing is consuming a live stream of data that we want to extract or aggregate some other data fr

【Quartz】Quartz概述及入门实例

林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka Quartz 在开源任务调度框架中的翘首,它提供了强大任务调度机制,难能可贵的是它同时保持了使用的简单性.Quartz 允许开发人员灵活地定义触发器的调度时间表,并可以对触发器和任务进行关联映射.        此外,Quartz提供了调度运行环境的持久化机制,可以保存并恢复调度现场,即使系统因故障关闭,任务调度现场数据并不会丢失.此外,Quartz还提供了组件式的侦听器.各种插件.线程池等

【Quartz】Quartz存储与持久化-基于quartz.properties的配置

林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 一.   Quartz存储与持久化 Quartz提供两种基本作业存储类型.第一种类型叫做RAMJobStore,第二种类型叫做JDBC作业存储.在默认情况下Quartz将任务调度的运行信息保存在内存中,这种方法提供了最佳的性能,因为内存中数据访问最快.不足之处是缺乏数据的持久性,当程序路途停止或系统崩溃时,所有运行的信息都会丢失. 比如我们希望安排一个执行100次的任务,如果执行到50次时系

【Quartz】Quartz存储与持久化-基于Spring的配置

林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 在上文[Quartz]Quartz存储与持久化-基于quartz.properties的配置,是通过配置quartz.properties文件的方式来实现持久化的.本文将通过Spring配置的方式来实现存储与持久化. 1.同上文一样,要先创建相关的数据表,并新建一个JAVA工程,并导入相关的包,整个工程目录 如下: 2.创建Job类 package com.mucfc; import jav