Scheduling quartz.net with Windows service tasks

Source: Internet
Author: User
Tags log4net

Windows services are written using standard CSharp, and the Task Scheduler framework uses open source quartz.net.
First create the Windows service-jobservice


Second, create the class library project-joblibrary
The overall solution architecture diagram is as follows:


Add Quartz.net's NuGet package reference in Joblibary, and when added, the VS will automatically add a series of dependencies that are necessary to not be deleted by hand.


Next add Common.Logging.Log4Net1211 NuGet package, he is another implementation of Log4net, will automatically add log4net dependency
All add-on packages such as:



Now add the task, add a job class to inherit Ijob, and implement its interface in Libary

  

Using system;using quartz;namespace joblibrary{public    class Job:ijob    {        private static readonly Common.Logging.ILog logger = Common.Logging.LogManager.GetLogger (System.Reflection.MethodBase.GetCurrentMethod (). DeclaringType);        public void Execute (Ijobexecutioncontext context)        {            try            {                logger. Info ("job start");                using (System.IO.StreamWriter SW = new System.IO.StreamWriter ("E:\\log.txt", True))                {                    sw. WriteLine (DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss") + "Eat---sleep");                }                Logger. Info ("Job End");             }            catch (Exception e)            {                logger. Error (E.message);}}}       

This class is the task you need to do. My task is to eat and sleep.

Then add the Joblibrary reference in the Jobservice and add the following code (you need to add the NuGet reference as well)

Using common.logging;using quartz;using quartz.impl;using system.serviceprocess;namespace JobService{public    Partial class Service1:servicebase    {        private IScheduler Scheduler;        Private readonly ILog logger;        Public Service1 ()        {            InitializeComponent ();            Ischedulerfactory schedulerfactory = new Stdschedulerfactory ();            Scheduler = Schedulerfactory.getscheduler ();            Logger = Logmanager.getlogger (GetType ());        }        protected override void OnStart (string[] args)        {            logger. Info ("Quartz service started successfully");            Scheduler. Start ();        }        protected override void OnStop ()        {            Scheduler. Shutdown (FALSE);}}}    

  

After the code is complete, you need to configure Quartz_jobs.xml, add the XML configuration file "Quartz_jobs.xml" to the Jobservice project, and add the task configuration.

<?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> <!--defining sample Tasks 1 job--> <job> <name>DemoJob1</name> <group>DeomJobGroup</group> <description>quartz.net Sample Task 1 </description> <job-type>JobLibrary.Job,JobLibrary</job-type> <durable>true</durable&      Gt      <recover>false</recover> </job> <!--define a sample Task 1 trigger to perform DemoJob1 tasks every 10 seconds---<trigger>        <cron> <name>DemoJob1Trigger</name> <group>DeomJobTriggerGroup</group> <job-name>demojob1</job-name> <job-group>DeomJobGroup</job-group> &LT;CRON-EXPRESSION&GT;0/10 * * * * * </cro n-expression> </cron> </trigger> </schedule></job-scheduling-data>

This configuration file has a puzzling bug, that is, the top few lines can not have a blank line, do not know what the situation, have to know the man hope to inform. Been this pit for half a day.

Second, when adding the Quartz.config configuration file

  

# can configure your scheduler in either<Quartz>configuration section# or in Quartz properties file# configuration sections has Precedencequartz.scheduler.instanceNa me = serverscheduler# 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 Contextquartz.scheduler.exporter.type = Quartz.Simpl.RemotingSchedulerExporter, Quartzquartz.scheduler.exporter.port = 555quartz.scheduler.exporter.bindname = QuartzSchedulerquartz.scheduler.exporter.channelType = Tcpquartz.scheduler.exporter.channelName = Httpquartz

And then the configuration of the Quartz config.

  

<configSections>    <section name= "quartz" type= "System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,culture=neutral, publickeytoken=b77a5c561934e089 "/>    <section name=" log4net "type=" Log4net. Config.log4netconfigurationsectionhandler, log4net "/>    <sectiongroup name=" common ">      <section Name= "Logging" type= "Common.Logging.ConfigurationSectionHandler, common.logging"/>    </sectionGroup>  </configSections>

And then the compilation, remember Quartz_jobs.xml and quartz.config these two files must be compiled output, or not read.

  

After you start, you can see what's written to the file.

If a machine is running on a task, then what if the machine hangs out? What happens if a task is run on more than one machine?

Scheduling quartz.net with Windows service tasks

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.