Use of Quartz.net

Source: Internet
Author: User
Tags set time log4net

Quartz.net Introduction

The Quartz.net job scheduling framework is a. NET extended ported version of the Quartz Scheduler project developed by the great organization Opensymphony.

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. Supports cron-like expressions, clusters, databases.

Download Project official website https://www.quartz-scheduler.net/

Getting Started with quartz.net

My demo download: https://github.com/yx09041/MyQuartz.git

We present a simple example of a timed task that outputs "My timed task test" every three seconds, as follows:

Operation Result:

Create a console program and install related packages

Install the following packages through the Package Manager

    • Quartz
    • Common.Logging.Log4Net1211
    • log4net
    • Topshelf
    • Topshelf.Log4Net

Overall structure of the project

Defining tasks

Define the task implementation ijob to execute the corresponding task logic, in the Execute method to write the business logic to be processed, the system will follow the quartz configuration, timed processing.

As the task here is to output the log "My timed task test", if there are multiple tasks to add more than one task class here (note to implement Ijob)

usinglog4net;usingQuartz;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacemyquartzjobs.quartzjobs{ Public Sealed classTestjob:ijob {Private ReadOnlyILog _logger = Logmanager.getlogger (typeof(testjob));  Public voidExecute (Ijobexecutioncontext context) {_logger.infoformat ("My timed task test"); }    }}
scheduling Tasks with Topshelf
usingQuartz;usingQuartz.impl;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingtopshelf;namespacemyquartzjobs{ Public Sealed classServicerunner:servicecontrol, Servicesuspend {Private ReadOnlyIScheduler Scheduler;  PublicServicerunner () {Scheduler=Stdschedulerfactory.getdefaultscheduler (); }         Public BOOLStart (Hostcontrol hostcontrol) {Scheduler.            Start (); return true; }         Public BOOLStop (Hostcontrol hostcontrol) {Scheduler. Shutdown (false); return true; }         Public BOOLContinue (Hostcontrol hostcontrol) {Scheduler.            Resumeall (); return true; }         Public BOOLPause (Hostcontrol hostcontrol) {Scheduler.            Pauseall (); return true; }    }}
View CodeProgram entry
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingtopshelf;namespacemyquartzjobs{classProgram {Static voidMain (string[] args) {log4net. Config.XmlConfigurator.ConfigureAndWatch (NewFileInfo (AppDomain.CurrentDomain.BaseDirectory +"Log4net.config")); Hostfactory.run (x={x.uselog4net (); X.service<ServiceRunner>(); X.setdescription ("My general-purpose timer service"); X.setdisplayname ("MyService"); X.setservicename ("My general-purpose timer service");            X.enablepauseandcontinue ();        }); }    }}
Configure the configuration file

Quartz.config, Quartz_jobs.xml, Log4net.config

Set the properties of three files to always copy

Quartz.config Configuration

The Quartz_jobs.xml configuration is set to execute once every 3 seconds

Specific configuration parameter description reference Quartz_jobs.xml configuration

Log4net.config is a common log component, and the configuration is no longer described here.

Service Run View effect

Run EXE program to see the effect of running

Install as a Windows service

Run the cmd command line in Administrator mode to switch to the corresponding program directory to run the following command to install/start and uninstall the service;

Installation: MyQuartzJobs.exe Install start: MyQuartzJobs.exe start uninstall: MyQuartzJobs.exe Uninstall

Open the Windows service to see the following, enable to run

Other quartz_jobs.xml configuring the job task

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
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.

Reference article:

Quartz.net Open Source Job scheduling framework use detailed

Create a Windows service using Topshelf

Quartz.net Getting Started

Use of Quartz.net

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.