Topshelf works with Quartz. NET to implement regular scheduling tasks on the server, topshelfquartz.net

Source: Internet
Author: User

Topshelf works with Quartz. NET to implement regular scheduling tasks on the server, topshelfquartz.net

This week, we accept a new requirement: regularly poll a third-party WebAPI in different time periods within one day, and save the results of the third-party WebAPI.

Demand Analysis: time period, timed start, timed end, and round robin. The main focus is on the first three. Polling is actually an Http request, which is better solved.

Technology Selection:

1. The simplest method is Windows Service, Timer, and HttpClient.
2. High Point Mode of B: Topshelf, Quartz. NET, and HttpClient.
The reason for choosing the second method:

1. I tried to write one for Windows Service, and found that the debugging of the additional process is indeed troublesome. In the future, if the requirement is changed, I need to re-Debug and release Windows Service.

2. Timer needs to be established in multiple projects, which is difficult to differentiate

3. just learning to use Quartz. NET, I plan to become an MVC version of the scheduling task management system in a short time.

4. After searching for the cnblog, we found that Topshelf can be used to write and Debug Programs in Console-based mode. After the program passes the debugging, we can use the Topshelf command to complete Windows Service installation, it is said that Mono can be installed on Linux, or cross-platform support (* ^_^ *) or Docker images.

Show Code:

1. Add dependency Nuget packages: Topshelf, Topshelf. Log4Net, Quartz, Common. Logging, Common. Logging. Core, Common. Logging. Log4Net1211, and log4Net.

2. Create ServiceRunner. cs class, which inherits ServiceControl and ServiceSuspend. This is to use Start (), Stop (), Continue (), and Pause () of Topshelf to execute the Start () for Z task scheduling respectively (), Shutdown (), ResumeAll (), PauseAll () method

1 public class ServiceRunner: ServiceControl, ServiceSuspend 2 {3 private readonly isched1_schedner; 4 public ServiceRunner () 5 {6 scheduler = StdSchedulerFactory. getdefaschscheduler (); 7} 8 public bool Continue (HostControl hostControl) 9 {10 scheduler. resumeAll (); 11 return true; 12} 13 14 public bool Pause (HostControl hostControl) 15 {16 scheduse. pauseAll (); 17 return true; 18} 19 20 public bool Start (HostControl hostControl) 21 {22 scheduler. start (); 23 return true; 24} 25 26 public bool Stop (HostControl hostControl) 27 {28 scheduler. shutdown (false); 29 return true; 30} 31}View Code

3. Here I use the Topshelf Custom Service Mode and write the following code in the Main () method:

1 HostFactory. run (x => 2 {3 x. useLog4Net (); 4 x. service <ServiceRunner> (); 5 x. setDescription ("QuartzDemo service description"); 6 x. setDisplayName ("QuartzDemo service display name"); 7 x. setServiceName ("QuartzDemo service name"); 8 9 x. enablePauseAndContinue (); 10 });View Code

4. By now, the creation of Windows Service is basically over, and the next step is to focus on how to use Quartz for a scheduled task. However, this process is not difficult. Here I use the Cron mode of Quartz. Compared with the Simple mode, this mode sets Trigger triggering and Job execution through configuration, after my Windows Service is created, I don't need to compile it again. I just need to replace it with a dynamic link library that implements the IJob interface and configure it in Quartz_jobs.xml. The test code for IJob implementation is as follows:

1 public class TestJob: IJob 2 {3 private readonly ILog _ log = LogManager. getLogger (typeof (TestJob); 4 public void Execute (IJobExecutionContext context) 5 {6 7 _ log. info ("test Job, time:" + DateTime. now. toString ("r"); 8 9} 10}View Code

5. Prepare Quartz. NET configuration file quartz. config, quartz_jobs.xml, And the Initialize () method of Quartz reads quartz from the compilation output directory by default. config File in quartz. add quartz to the config file. plugin. xml. fileNames node write ~ /Quartz_jobs.xml, used to configure Trigger and Job execution

1 # You can configure your scheduler in either <quartz> configuration section 2 # or in quartz properties file 3 # Configuration section has precedence 4 5 quartz. scheduler. instanceName = QuartzTest 6 7 # configure thread pool info 8 quartz. threadPool. type = Quartz. simpl. simpleThreadPool, Quartz 9 quartz. threadPool. threadCount = 1010 quartz. threadPool. threadPriority = Normal11 12 # job initializati On plugin handles our xml reading, without it defaults are used13 quartz. plugin. xml. type = Quartz. Plugin. Xml. XMLSchedulingDataProcessorPlugin, Quartz14 quartz. plugin. xml. fileNames = ~ /Quartz_jobs.xml15 16 # export this server to remoting context17 # quartz. scheduler. exporter. type = Quartz. simpl. remotingSchedulerExporter, Quartz18 # quartz. scheduler. exporter. port = 55519 # quartz. scheduler. exporter. bindName = QuartzScheduler20 # quartz. scheduler. exporter. channelType = tcp21 # quartz. scheduler. exporter. channelName = httpQuartzQuartz. config 1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 3 <! -- This file contains job definitions in schema version 2.0 format --> 4 5 <job-scheduling-data xmlns = "http://quartznet.sourceforge.net/JobSchedulingData" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" version = "2.0"> 6 7 <processing-directives> 8 <overwrite-existing-data> true </overwrite-existing-data> 9 </processing- directives> 10 11 <schedule> 12 13 <! -- TestJob Test task configuration --> 14 <job> 15 <name> TestJob </name> 16 <group> Test </group> 17 <description> TestJob Test </description> 18 <job-type> WindowsService. testJob, windows Service </job-type> 19 <durable> true </durable> 20 <recover> false </recover> 21 </job> 22 <trigger> 23 <cron> 24 <name> TestJobTrigger </name> 25 <group> Test </group> 26 <job-name> TestJob </job-name> 27 <job-group> Test </job- group> 28 <! -- <Start-time> 2017-08-03T16: 00: 00 + 16: 00 </start-time> 29 <end-time> 2017-08-03T18: 10: 00 + 18: 10 </end-time> --> 30 <cron-expression> 0/3*0-6 **? </Cron-expression> 31 </cron> 32 </trigger> 33 34 </schedule> 35 </job-scheduling-data>Quartz_jobs.xml

6. Now, we can basically run the project, but this can only be seen on the console to print a line of "test Job, time: ***" every three seconds :***", it cannot be determined that the scheduled task can also be executed according to the plan when running Windows Service. We also need to output logs to the file and continue to configure log4Net

1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <configuration> 3 <configSections> 4 <section name = "log4net" type = "log4net. config. log4NetConfigurationSectionHandler, log4net "/> 5 </configSections> 6 7 <log4net> 8 <appender name =" RollingLogFileAppender "type =" log4net. appender. rollingFileAppender "> 9 <! -- Log Path --> 10 <param name = "File" value = "F: \ App_Log \ servicelog \"/> 11 <! -- Whether to append logs to the file --> 12 <param name = "AppendToFile" value = "true"/> 13 <! -- Without UTF-8 Encoding, Chinese characters are displayed as garbled characters --> 14 <param name = "Encoding" value = "UTF-8"/> 15 <! -- Log Retention days --> 16 <param name = "MaxSizeRollBackups" value = "10"/> 17 <! -- Whether the log file name is fixed --> 18 <param name = "StaticLogFileName" value = "false"/> 19 <! -- Log file name format: 2008-08-31.log --> 20 <param name = "DatePattern" value = "yyyy-MM-dd & quot ;. read. log & quot; "/> 21 <! -- Rolling logs by Date --> 22 <param name = "RollingStyle" value = "Date"/> 23 <layout type = "log4net. layout. patternLayout "> 24 <param name =" ConversionPattern "value =" % d [% t] %-5 p % c-% m % n % loggername "/> 25 </layout> 26 </appender> 27 28 <! -- Log displayed on the console --> 29 <appender name = "ColoredConsoleAppender" type = "log4net. appender. coloredConsoleAppender "> 30 <mapping> 31 <level value =" ERROR "/> 32 <foreColor value =" Red, highIntensity "/> 33 </mapping> 34 <mapping> 35 <level value =" Info "/> 36 <foreColor value =" Green "/> 37 </mapping> 38 <layout type = "log4net. layout. patternLayout "> 39 <conversionPattern value =" % n % date {HH: mm: ss, fff} [%-5 level] % m "/> 40 </l Ayout> 41 42 <filter type = "log4net. filter. levelRangeFilter "> 43 <param name =" LevelMin "value =" Info "/> 44 <param name =" LevelMax "value =" Fatal "/> 45 </filter> 46 </appender> 47 48 <root> 49 <! -- (High) OFF> FATAL> ERROR> WARN> INFO> DEBUG> ALL (low) --> 50 <level value = "all"/> 51 <appender-ref = "ColoredConsoleAppender"/> 52 <appender-ref = "RollingLogFileAppender"/> 53 </root> 54 </log4net> 55 </configuration>Log4net. config

Add a line of code in the Main () method to read the log4Net configuration file:Quartz. config, quartz_jobs.xml, and log4net. config files, select → right-click Properties → copy to input directory to always copy

1 static void Main (string [] args) 2 {3 log4net. config. xmlConfigurator. configureAndWatch (new FileInfo (AppDomain. currentDomain. baseDirectory + "log4net. config "); 4 HostFactory. run (x => 5 {6 x. useLog4Net (); 7 x. service <ServiceRunner> (); 8 x. setDescription ("QuartzDemo service description"); 9 x. setDisplayName ("QuartzDemo service display name"); 10 x. setServiceName ("QuartzDemo service name"); 11 12 x. enablePauseAndContinue (); 13}); 14}View Code

Finally, we need to register Topshelf to Windows and open the debug folder in CMD. The Topshelf command is as follows,

Install: WindowsService.exe install start: WindowsService.exe start uninstall: WindowsService.exe uninstall this point is basically complete. Next I only need to implement the Business Code in a class that inherits IJob. (* ^_^ *) Reference

Quartz. NET

Official Document: Topself document: http://topshelf-project.com/log4netdocument: http://logging.apache.org/log4net/

 

Related Article

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.