Quartz.net Getting Started

Source: Internet
Author: User
Tags log4net

Go from: http://www.cnblogs.com/jys509/p/4628926.html overview

Quartz.net is an open source job scheduling framework, which is very suitable for routine polling of database synchronization, timed email notification, and timed processing of data. Quartz.net allows developers to schedule jobs based on time intervals (or days). It implements a many-to-many relationship between jobs and triggers, and also associates multiple jobs with different triggers. Applications that integrate quartz.net can reuse jobs from different events and can combine multiple jobs for an event.

Reference

Official Learning Document: http://www.quartz-scheduler.net/documentation/index.html

Introduction to use Examples: http://www.quartz-scheduler.net/documentation/quartz-2.x/quick-start.html

Official source code Download: http://sourceforge.net/projects/quartznet/files/quartznet/or to my uploaded csdn download: http://download.csdn.net/ detail/jys1216/8878305

To download the official example, let us analyze:

After unpacking, see the document

When you open it, you see the following project structure:

Projects can be run directly:

After running, we can see that there is output every 10 seconds, because, in the configuration quart.net service file, it is configured to execute every 10 seconds.

Quickly build a quartz first step: Install

After you create a new Quartzdemo project, install the following package

    • Install-Package Quartz
    • Install-Package Common.Logging.Log4Net1211
    • Install-Package log4net
    • Install-Package Topshelf
    • Install-Package Topshelf.Log4Net

Quartz rely on common.logging and Common.Logging.Log4Net1211, and because Log4net is a relatively standard logging tool, so we usually install log4net , in addition to scheduled jobs are generally allowed in the background service, So we also installed the topshelf.

Step two: Realize Ijob

TestJob.cs implementation Ijob, in the Execute method to write the business logic to be processed, the system will follow the quartz configuration, timed processing.

Using log4net;using quartz;using system;using system.collections.generic;using system.linq;using System.Text;using System.threading.tasks;namespace quartzdemo.quartzjobs{public    sealed class Testjob:ijob    {        private ReadOnly ILog _logger = Logmanager.getlogger (typeof (Testjob));        public void Execute (Ijobexecutioncontext context)        {            _logger.infoformat ("Testjob test");        }    }}
Step three: Scheduling tasks with Topshelf

Introduction to the use of topshelf, please see my other times introduction: http://www.cnblogs.com/jys509/p/4614975.html

ServiceRunner.cs

Using quartz;using quartz.impl;using system;using system.collections.generic;using system.linq;using System.Text; Using system.threading.tasks;using topshelf;namespace quartzdemo{public    sealed class Servicerunner: ServiceControl, Servicesuspend    {        private readonly IScheduler Scheduler;        Public Servicerunner ()        {            scheduler = Stdschedulerfactory.getdefaultscheduler ();        }        public bool Start (Hostcontrol Hostcontrol)        {            Scheduler. Start ();            return true;        }        public bool Stop (Hostcontrol Hostcontrol)        {            Scheduler. Shutdown (false);            return true;        }        public bool Continue (Hostcontrol Hostcontrol)        {            Scheduler. Resumeall ();            return true;        }        public bool Pause (Hostcontrol Hostcontrol)        {            Scheduler. Pauseall ();            return true;}}    }
Fourth Step: Program entry
Namespace quartzdemo{    class program    {        static void Main (string[] args)        {            log4net. Config.XmlConfigurator.ConfigureAndWatch (New FileInfo (AppDomain.CurrentDomain.BaseDirectory + "Log4net.config"));            Hostfactory.run (x =            {                x.uselog4net ();                X.service<servicerunner> ();                X.setdescription ("Quartzdemo service description");                X.setdisplayname ("Quartzdemo Service display Name");                X.setservicename ("Quartzdemo service Name");                X.enablepauseandcontinue ();}            );}}    
Fifth Step: Configure Quartz.config, Quartz_jobs.xml, Log4net.config

Description: These three files, select → right-click properties → copy to input directory set to: Always copy

Quartz.config
# can configure your scheduler in either <quartz> configuration section# or in Quartz properties file# Configura tion section has precedencequartz.scheduler.instanceName = quartztest# Configure thread pool Infoquartz.threadPool.type = Quartz.Simpl.SimpleThreadPool, Quartzquartz.threadPool.threadCount = 10quartz.threadpool.threadpriority = normal# Job Initialization plugin handles our XML reading, without it defaults is Usedquartz.plugin.xml.type = Quartz.Plugin.Xml. Xmlschedulingdataprocessorplugin, Quartzquartz.plugin.xml.fileNames = ~/quartz_jobs.xml# Export this server to Remoting Context#quartz.scheduler.exporter.type = Quartz.Simpl.RemotingSchedulerExporter, quartz# Quartz.scheduler.exporter.port = 555#quartz.scheduler.exporter.bindname = quartzscheduler# Quartz.scheduler.exporter.channelType = Tcp#quartz.scheduler.exporter.channelname = Httpquartz
Quartz_jobs.xml
<?xml version= "1.0" encoding= "UTF-8"?><!--This file contains job definitions in schema version 2.0 format-- <job-scheduling-data xmlns= "Http://quartznet.sourceforge.net/JobSchedulingData" xmlns:xsi= "http://www.w3.org/ 2001/xmlschema-instance "version=" 2.0 "> <processing-directives> <overwrite-existing-data>true</ Overwrite-existing-data> </processing-directives> <schedule> <!--testjob Test task configuration-<jo b> <name>TestJob</name> <group>Test</group> <description>testjob test </des Cription> <job-type>QuartzDemo.QuartzJobs.TestJob,QuartzDemo</job-type> <durable>true</d urable> <recover>false</recover> </job> <trigger> <cron> <name& Gt        Testjobtrigger</name> <group>Test</group> <job-name>TestJob</job-name> <job-group>test</job-group&Gt <start-time>2015-01-22T00:00:00+08:00</start-time> &LT;CRON-EXPRESSION&GT;0/3 * * * *? </cron-expres sion> </cron> </trigger> </schedule></job-scheduling-data>
Log4net.config
<?xml version= "1.0" encoding= "Utf-8"?><configuration> <configSections> <section name= "Log4net" Type= "Log4net. Config.log4netconfigurationsectionhandler, log4net "/> </configSections> <log4net> <appender name= "Rollinglogfileappender" type= "log4net.      Appender.rollingfileappender > <!--log path--<param name= "File" value= "D:\App_Log\servicelog\"/> <!--whether to append the log to the file--<param name= "Appendtofile" value= "true"/> <!--log retention days--&LT;PA Ram Name= "maxsizerollbackups" value= "/> <!--log file name is fixed---<param name=" Staticlogfilename "V Alue= "false"/> <!--log file name format is:2008-08-31.log--> <param name= "Datepattern" value= "yyyy-mm-dd&quo t;. read.log&quot; " /> <!--logs by date scrolling-<param name= "Rollingstyle" value= "date"/> <layout type= "log4net. Layout.patternlayout "> <param name=" Conversionpattern "value="%d[%t]%-5p%c-%m%n%loggername "/> </layout> </appender> <!--console display logs--<append Er name= "coloredconsoleappender" type= "log4net. Appender.coloredconsoleappender "> <mapping> <level value=" ERROR "/> <forecolor value= "Red, highintensity"/> </mapping> <mapping> <level value= "Info"/> <forec Olor value= "Green"/> </mapping> <layout type= "log4net. Layout.patternlayout "> <conversionpattern value="%n%date{hh:mm:ss,fff} [%-5level]%m "/> </layout&      Gt <filter type= "log4net. Filter.levelrangefilter "> <param name=" levelmin "value=" Info "/> <param name=" Levelmax "value=" F Atal "/> </filter> </appender> <root> <!--(high) OFF > FATAL > ERROR > WARN > INFO > DEBUG > All (Low)--<level value= "All"/> <appender-ref ref= "ColoredcoNsoleappender "/> <appender-ref ref=" Rollinglogfileappender "/> </root> </log4net></configu Ration>
After running, the effect is output every 3 seconds

Finally, it is installed as a Windows service. Specific installation reference: Http://www.cnblogs.com/jys509/p/4614975.html

SOURCE Download: http://download.csdn.net/download/jys1216/8882315

Quartz Configuring Quartz_jobs.xmljob Tasks

In fact, the 1.x version of the <JOB-DETAIL>, this node is used to define each specific task, multiple tasks Please create multiple job nodes to

    • Name (required), the names of multiple jobs in the same group cannot be the same, and if group is not set, all job without group is the same group, such as:<name>samplejob</name>
    • Group (optional) tasks belong to groups that identify the groups to which the task belongs, such as:<group>samplegroup</group>
    • Description (optional) task description, which describes the specific contents of the task, such as: <description>sample job for Quartz server</description>
    • Job-type (required) task type, the specific type of task and its owning assembly, format: the class name that implements the Ijob interface that contains the full namespace, the assembly name, such as: <job-type>quartz.server.samplejob, Quartz.server</job-type>
    • Durable (optional) The specific function is not known, the official example defaults to true, such as:<durable>true</durable>
    • Recover (optional) The specific role is not known, the official example defaults to false, such as:<recover>false</recover>
Trigger Task Trigger

Used to define which way to start a task (job), the same job can define multiple trigger, multiple trigger separate execution schedules, each trigger must and can define only one type of trigger (Calendar-interval, simple, Cron

Calendar-interval a trigger type that uses fewer, less-than-simple-task triggers that can dispatch tasks for repetitive executions
    • Name (required) trigger names, names must be different in the same group
    • Group (optional) Trigger groups
    • Description (optional) trigger description
    • Job-name (required) The task name to be dispatched, the job-name must be exactly the same as the name in the corresponding job node
    • Job-group (optional) the group to which the dispatch task (Job) belongs, which must be exactly the same as the group in the job
    • Start-time (optional) task start execution time UTC time, Beijing time needs +08:00, such as:<start-time>2012-04-01t08:00:00+08:00</start-time> Beijing time April 1, 2012 8:00 start execution, note that this property will be detected when the service starts or restarts, if this property is not set or the Start-time setting is earlier than the current time, the service starts immediately after the start of the schedule, if the time is set later than the current time, The service will wait for the same set time before the task is executed for the first time, generally do not set this property if there is no special need
    • Repeat-count (required) The number of task executions, such as:<repeat-count>-1</repeat-count> for unlimited execution, <repeat-count>10</ Repeat-count> represents 10 executions
    • Repeat-interval (required) task trigger interval (milliseconds), such as:<repeat-interval>10000</repeat-interval> executed every 10 seconds
Cron Complex task trigger-customizing task scheduling with Cron expressions (highly recommended)
    • Name (required) trigger names, names must be different in the same group
    • Group (optional) trigger groups D
    • Escription (optional) Trigger description
    • Job-name (required) The task name to be dispatched, the job-name must be exactly the same as the name in the corresponding job node
    • Job-group (optional) the group to which the dispatch task (Job) belongs, which must be exactly the same as the group in the job
    • Start-time (optional) task start execution time UTC time, Beijing time needs +08:00, such as:<start-time>2012-04-01t08:00:00+08:00</start-time> Indicates that the property will be detected when the service starts or restarts on April 1, 2012 8:00, and if this property is not set, the service performs a task schedule based on the Cron-expression settings, and if the Start-time is set earlier than the current time, After the service starts, it ignores the cron-expression setting, executes the dispatch immediately, and then executes the task schedule according to Cron-expression, and if the set time is later than the current time, the service will be applied after the same setting time is reached Cron-expression , perform task scheduling according to the rules, do not set this property if there is no special need
    • Cron-expression (required) cron expression, such as: <CRON-EXPRESSION>0/10 * * * * *?</cron-expression> every 10 seconds
Cron Expressions for Quartz

Official English introduction Address: http://www.quartz-scheduler.net/documentation/quartz-2.x/tutorial/crontrigger.html

Cron expressions on the whole is very easy to understand, only a little attention: "?" The use of the number, see below to Know "? "Can be used in day of month and day of week, he is mainly to solve the following scenarios, such as: 1th every month 31 minutes per hour, the correct expression is: * 31 * 1 *? , and cannot be: * 31 * 1 *, as this represents any day of the week.


Consists of 7 segments: The second day of the Month and the Moon (optional)
"-": The range mon-wed represents Monday to Wednesday
",": The enumeration Mon,web represents Monday and Wednesday
"*": Table is "per", monthly, daily, weekly, yearly etc.
"/": Represents the Increment: 0/15 (in minutes) every 15 minutes, starting after 0 minutes, 3/20 every 20 minutes, starting from 3 minutes later
"?": can only appear in the day, week segment, indicating that no specific value is specified
"L": can only appear in the day, the week paragraph inside, is the last abbreviation, one months of the final day, one weeks last day (Saturday)
"W": Indicates weekday, the most recent working day from the given value
"#": Represents the first few weeks of one months, for example: "6#3" means the third Friday of each month (1=sun ... 6=FRI,7=SAT)

Official examples
Expression meaning
0 0 12 * *? Triggered 12 o'clock noon every day
0 15 10? * * Triggered 10:15 daily
0 15 10 * *? Triggered 10:15 daily
0 15 10 * *? * Triggered 10:15 daily
0 15 10 * *? 2005 2005-10:15 trigger per day
0 * 14 * *? Triggers every 1 minutes from 2 o'clock in the afternoon to 2:59 daily
0 0/5 14 * *? Triggers every 5 minutes from 2 o'clock in the afternoon to 2:55 daily
0 0/5 14,18 * *? Every 5 minutes from 2 o'clock in the afternoon to 2:55 daily and from 6 o'clock in the afternoon to 6:55
0 0-5 14 * *? Triggers every 1 minutes from 2 o'clock in the afternoon to 2:05 daily
0 10,44 14? 3 WED Every March, Wednesday, 2:10 and 2:44 triggers.
0 15 10? * Mon-fri 10:15 trigger from Monday to Friday
0 15 10 15 *? 15th 10:15 per month, triggered
0 L *? 10:15 trigger on the last day of the month
0 L-2 *? Fire at 10:15am in the 2nd-to-last last day of every month
0 15 10? * 6L Last month of Friday 10:15 Trigger
0 15 10? * 6L Fire at 10:15am in the last Friday of every month
0 15 10? * 6L 2002-2005 2002 to 2005 the last Friday 10:15 trigger
0 15 10? * 6#3 The third Friday 10:15 of the month is triggered
0 0 12 1/5 *? Fire at 12pm (noon) Every 5 days every month, starting on the first day of the month.
0 11 11 11 11? Fire every November 11th at 11:11am.

Source code download and information you may need to know

SOURCE Download: http://download.csdn.net/download/jys1216/8882315

Topself Introduction: http://www.cnblogs.com/jys509/p/4614975.html

Log4net Introduction: http://www.cnblogs.com/jys509/p/4569874.html

Quartz.net Getting Started

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.