In some cases, we usually need the software to have a function to automatically execute certain tasks, but we do not want to start the software directly or start the software manually every time, now we can consider windows Services.
First, create a windows Service Project (for more information, see:C # basic tutorial on creating a Windows Service)
In the created Project, click "Click here to switch to Code view" to switch to the Code view.
We mainly focus on two methods:
• OnStart-Control Service Startup
• OnStop-Control Service stop
Example:
1 public partial class Service1: ServiceBase 2 {3 public Service1 () 4 {5 InitializeComponent (); 6} 7 8 protected override void OnStart (string [] args) 9 {10 // todo: Here is the code executed by the Service Startup 11} 12 13 protected override void OnStop () 14 {15 // todo: code 16 executed by the Service stop} 17}View Code
Now we can write a scheduled task:
1 private void StartDoSomething () 2 {3 System. timers. timer timer = new System. timers. timer (10000); // interval of 10 seconds 4 timer. autoReset = true; 5 timer. enabled = false; // run 6 timer at a time. elapsed + = new ElapsedEventHandler (ExecutionCode); 7 timer. start (); 8} 9 10 private void ExecutionCode (object source, System. timers. elapsedEventArgs e) 11 {12 string dtNow = DateTime. now. toString ("HH: mm"); 13 if (dtNow = "12:00") 14 {15 File. writeAllText ("D:/ExecutionService.txt", "The service executes a task", Encoding. UTF8); 16} 17}
Then, call the StartDoSomething method in the OnStart method.
1 protected override void OnStart(string[] args)2 {3 StartDoSomething();4 }
The above can be regarded as a simple windows Service for scheduled task execution, but it is not perfect here. It is not good to use Timer in the service, so we can use Quartz. net to implement the task scheduling function.
First, we will introduce the Quartz. Net Framework:
Introduction: Quartz. Net is an open-source task scheduling framework. It is very powerful and can help us with scheduled and specific operations through simple configuration. Compared with the while (true) in the thread we use and sleep to execute an operation, it should be regarded as high-end, atmospheric, and high-grade. At present, the latest version is 2.2. Some method names in the new version have changed. People who use the latest version should have some experience. here I use Quartz.net in the most common and stable way, and configure the trigger in the Windows service. (The above content is taken from the Internet)
A simple understanding is that it can help us do things at regular intervals, which is equivalent to an alarm that can wake us up.
The latest version is Quartz. NET 2.2.3. You can download it here.
Now we need to reference the following file in the service project we just created:
Write your own configuration in the configuration file (This example demonstrates regular access to a specified website)
1 <? Xml version = "1.0"?> 2 <configuration> 3 <configSections> 4 <sectionGroup name = "JobList"> 5 <section name = "Job" type = "MyService1101.MyConfigHandler, myService1101 "/> 6 </sectionGroup> 7 </configSections> 8 <startup> 9 <supportedRuntime version =" v4.0 "sku = ". NETFramework, Version = v4.5 "/> 10 </startup> 11 <JobList> 12 <Job> <! -- Here is a task node --> 13 <add key = "Url" value = "http://www.baidu.com"/> <! -- Url to be accessed --> 14 <add key = "Hour" value = "10"/> <! -- Start Time Hour. Note: The hour here is 0-23. If it is, it is 1, instead of 01 --> 15 <add key = "Minute" value = "30"/> <! -- Start time in minutes. Note: Same as above 0-59 --> 16 </Job> 17 </JobList> 18 </configuration>View Code
Create a new MyConfigHandler. cs class to read custom configuration nodes
1 public class MyConfigHandler: IConfigurationSectionHandler 2 {3 public MyConfigHandler () 4 {5} 6 7 public object Create (object parent, object configContext, System. xml. xmlNode section) 8 {9 NameValueCollection configs; 10 NameValueSectionHandler baseHandler = new NameValueSectionHandler (); 11 configs = (NameValueCollection) baseHandler. create (parent, configContext, section); 12 return configs; 13} 14}View Code
Create a SystemScheduler class to create a scheduler.
1 public class SystemScheduler 2 {3 private SystemScheduler () 4 {5} 6 7 public static SystemScheduler CreateInstance () 8 {9 return new SystemScheduler (); 10} 11 12 private IScheduler _ scheduler; 13 14 public void StartScheduler () 15 {16 // The task start time in the configuration file is 17 int hour = int. parse (NameValueCollection) ConfigurationSettings. getConfig ("JobList/Job") ["Hour"]); 18 int minute = int. parse (NameValueCollection) ConfigurationSettings. getConfig ("JobList/Job") ["Minute"]); 19 20 ISchedulerFactory schedulerFactory = new StdSchedulerFactory (); // 21 _ scheduler = schedulerFactory for memory scheduling. getScheduler (); 22 23 // create a Job to execute a specific task 24 IJobDetail synchronousData = new JobDetailImpl ("SynchronousData", typeof (SynchronousData )); 25 // create and define the trigger rule (the execution time is: hour: minute) 26 ITrigger trigger = 27 TriggerBuilder. create () 28. withDailyTimeIntervalSchedule (29 a =>. withIntervalInHours (24 ). onEveryDay (). startingDailyAt (TimeOfDay. hourAndMinuteOfDay (hour, minute ))). build (); 30 // Add the created task and trigger rule to Quartz 31 _ scheduler. scheduleJob (synchronousData, trigger); 32 // start 33 _ scheduler. start (); 34} 35 36 public void StopScheduler () 37 {38 _ scheduler. shutdown (); 39} 40}View Code
Create a new SynchronousData class to implement the IJob interface to implement custom tasks in SystemScheduler.
1 public class SynchronousData: IJob 2 {3 public void Execute (IJobExecutionContext context) 4 {5 string Url = (NameValueCollection) ConfigurationSettings. getConfig ("JobList/Job") ["Url"]; 6 WebClient wc = new WebClient (); 7 WebRequest wr = WebRequest. create (new Uri (Url); 8 using (StreamWriter sw = File. appendText (@ "d: \ SchedulerService.txt") 9 {10 sw. writeLine ("------------------" + "MyService service in:" + DateTime. now. toString ("yyyy-MM-dd HH: mm: ss") + "executed a task" + "----------------"); 11 sw. flush (); 12} 13} 14}View Code
Finally, add the application to the scheduler in OnStart.
1 protected override void OnStart(string[] args)2 {3 SystemScheduler _systemScheduler = SystemScheduler.CreateInstance();4 _systemScheduler.StartScheduler();5 }
After the program is generated, run the command to install it.
After the installation is complete, a new service item will appear in the service.
After the program runs, A schedulerservice.txt file is generated on the D: disk.
Source code: Download