In our usual projects often encounter timed tasks, such as timing synchronization data, scheduled backup data, timing statistics, and so on, scheduled tasks we all know the use of Quartz.net, this series is also quartz, but before we first use other ways to do a simple scheduled task to get started.
First of all, we now write a simple scheduled cycle of tasks, not much to say, directly on the code:
First step: Create a project and a new class library: we named Taskbase
Part II: Add an abstract base class Basemonitor:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacetaskbase{/// <summary> ///monitoring the underlying abstract class/// </summary> Public Abstract classBasemonitor {protectedSystem.Threading.Thread _thread; /// <summary> ///Monitoring time interval (milliseconds)/// </summary> Public Virtual intInterval {Get;Set; } Public Virtual stringName {Get;Set; } /// <summary> ///Monitor Status/// </summary> Public VirtualTaskstate State {Get;Set; } PublicBasemonitor (stringname) {Name=name; _thread=NewSystem.Threading.Thread (Baserun); _thread. IsBackground=true;//Gets or sets a value that indicates whether a thread is a background thread _thread. Start (); State=Taskstate. Operation; } Private voidBaserun () { while(state==taskstate. Run) {Try{Run (); System.Threading.Thread.Sleep (Interval); } Catch(Exception ex) { state=taskstate. Exceptions; PCore.Log.LogTextHelper.WriteErrorLog ( This. GetType (). Name +"monitoring error, this monitor is paused! ", ex); } } } protected Virtual voidRun () {} }}
(PCore.Log.LogTextHelper.WriteErrorLog in the code is a way to write a text log, and you can write this method yourself.) )
Note: This timed task base class is implemented with System.Threading.Thread, where Taskstate is an enumeration that represents the status of a task:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacetaskbase{ Public enumTaskstate {not started=0, run=1, pausing=2, the exception=3 }}
Part III: Add a Testmontior class that inherits Basemonitor, with the following code:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacetaskbase{ Public classTestmontior:basemonitor {/// <summary> ///constructor Function/// </summary> /// <param name= "name" >Detector Name</param> PublicTestmontior (stringName):Base(name) {}/// <summary> ///Monitoring time interval (milliseconds)/// </summary> Public Override intInterval {Get { returnGlobalconfig.testmonitorinterval; } } Public Override stringName {Get { return Base. Name; } Set { Base. Name =value; } } Public Overridetaskstate State {Get { return Base. State; } Set { Base. State =value; } } protected Override voidRun () {PCore.Log.LogTextHelper.WriteLog ("testmontitor Monitor is monitoring"); } }}
Note: Testmontior is equivalent to our job, and GlobalConfig in the code is a global parameter class that I define:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacetaskbase{ Public Static classGlobalConfig { Public Static intTestmonitorinterval {Get{return -*Ten; } } Public StaticList<basemonitor> Monitor =NewList<basemonitor>(); }}
This is what it looks like after creation:
The base Class library for timed tasks has been created, so let's look at how to use it.
Fourth: Use in the Web: Create a Web MVC project, reference Taskbase, and add the following code in Global.asax:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSYSTEM.WEB.MVC;usingSystem.Web.Optimization;usingSystem.Web.Routing;namespacewebtasktest{ Public classMvcApplication:System.Web.HttpApplication {protected voidApplication_Start () {arearegistration.registerallareas (); Filterconfig.registerglobalfilters (globalfilters.filters); Routeconfig.registerroutes (routetable.routes); Bundleconfig.registerbundles (Bundletable.bundles); TASKBASE.GLOBALCONFIG.MONITOR.ADD (NewTaskbase.testmontior ("Testing Monitor Test"));//Registering timed Tasks } }}
Run the Web site and view the log as follows:
You can see the execution once a second, because we set it in Globalconfig.testmonitorinterval for one second.
Let's look at how to use it in Windows Server:
Create a Windowsservertest class library, reference Taskbse, and add a Windows service:
usingQuartz;usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Diagnostics;usingSystem.Linq;usingsystem.serviceprocess;usingSystem.Text;usingSystem.Threading.Tasks;namespacewindowsservertest{Partial classTestservice:servicebase { PublicTestservice () {InitializeComponent (); } protected Override voidOnStart (string[] args) { Try { //TODO: Add code here to start the service. PCore.Log.LogTextHelper.WriteLog ("onstart:test service start ..."); TASKBASE.GLOBALCONFIG.MONITOR.ADD (NewTaskbase.testmontior ("Testing Monitor Test"));//Registration Monitor } Catch(Exception ex) {PCore.Log.LogTextHelper.WriteErrorLog ("something went wrong.", ex); } } protected Override voidOnStop () {//TODO: Add code here to perform the close operation required to stop the service. PCore.Log.LogTextHelper.WriteLog ("onstop:test Service End ..."); } protected Override voidOnPause () {PCore.Log.LogTextHelper.WriteLog ("onpause:test Service paused ..."); } protected Override voidOnContinue () {PCore.Log.LogTextHelper.WriteLog ("oncontinue:test Service continues ..."); } }}
About the Windows service on the loading and unloading can self-Baidu, no more beep.
After the installation of the service starts, we look at the following log:
In this section we have simply done a timed task, and we will introduce the Quartz.net task framework in the next chapter. (The source code will be uploaded with the following example), please continue to follow the chapter.
. NET Task Scheduler Quartz Series (1)-Self-built timed tasks