C#-Windows服务创建和运行

Windows服务创建和运行
 
 适用场景
ASP.Net通常是一个无状态的提供程序,不支持持续运行代码或者定时执行某段代码,所以我们需要构建自己的Windows服务来运行那些定时任务。
项目中需要定时处理数据时可以使用服务,比如短信发送,邮件提醒,和其他信息系统集合对接等定时任务
 
话不多说,简单介绍如何创建
 
1.新建服务
从 Visual Studio“文件”菜单中,选择“新建” > “项目”(或按 Ctrl+Shift+N),打开“新建项目”窗口
导航到并选择“Windows 服务 (.NET Framework)”项目模板。 
 
2.更改服务名称
右击“属性”,找到“ServiceName”属性,修改成“MyService”
 
3.添加安装程序
(1)右击“Service.cs[设计]”窗口,选择“添加安装程序”。
可以看见项目中自动多了“serviceProcessInstall1”,"serviceInstaller1"这两个文件。
 
(2) 设置组件serviceProcessInstaller1的主要属性,Accout:账户类型,LocalSystem本地系统服务;
 
4.添加项目需要的业务代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.ServiceProcess;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 namespace WindowsService
 8 {
 9     static class Program
10     {
11         /// <summary>
12         /// 应用程序的主入口点。
13         /// </summary>
14         static void Main()
15         {
16             ServiceBase[] ServicesToRun;
17             ServicesToRun = new ServiceBase[]
18             {
19                 new Service1()
20             };
21             ServiceBase.Run(ServicesToRun);
22         }
23     }
24 }

打开“Program.cs”,可以看到服务启动后,首先执行Service1。

这里,我们已5秒钟一个轮询,写一条日志信息为例
(1)首先添加文件夹“Utils”,添加类“Common.cs”,用于记录日志
 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 namespace WindowsService.Utils
 8 {
 9     public static class Common
10     {
11         public static void WriteLogs(string content)
12         {
13             string path = AppDomain.CurrentDomain.BaseDirectory;
14             string LogName =  System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace.Split('.')[0];
15             string[] sArray = path.Split(new string[] { LogName },  StringSplitOptions.RemoveEmptyEntries);
16             string aa = sArray[0] + "\\" + LogName + "Log\\";
17             path = aa;
18             if (!string.IsNullOrEmpty(path))
19             {
20                 if (!Directory.Exists(path))
21                 {
22                     Directory.CreateDirectory(path);
23                 }
24                 path = path + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";//
25                 if (!File.Exists(path))
26                 {
27                     FileStream fs = File.Create(path);
28                     fs.Close();
29                 }
30                 if (File.Exists(path))
31                 {
32                     StreamWriter sw = new StreamWriter(path, true,  System.Text.Encoding.Default);
33                     sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "----" +  content + "\r\n");
34                     sw.Close();
35                 }
36             }
37         }
38     }
39 }

 

 
(2)创建业务代码类“HandleService.cs”
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using WindowsService.Utils;
 7 namespace WindowsService
 8 {
 9     public class HandleService
10     {
11         public static void ActionRun(ref bool isRun)
12         {
13             try {
14                 isRun = true;
15                 //业务代码
16                 Common.WriteLogs("这是一条日志");
17               
18             }
19             catch (Exception ex)
20             {
21                 Common.WriteLogs(ex.Message);
22             }
23             finally
24             {
25                 isRun = false;
26             }
27         }
28     }
29 }

 

(3)设置Service1的定时触发功能,
需要添加定时器Timer,定时执行上一步创建的“HandleService.cs”中的业务逻辑,完整代码如下
 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Diagnostics;
 6 using System.Linq;
 7 using System.ServiceProcess;
 8 using System.Text;
 9 using System.Threading.Tasks;
10 using WindowsService.Utils;
11 namespace WindowsService
12 {
13     public partial class Service1 : ServiceBase
14     {
15         public Service1()
16         {
17             InitializeComponent();
18         }
19         System.Timers.Timer _timer = new System.Timers.Timer();
20         private bool isRun = false;
21         protected override void OnStart(string[] args)
22         {
23             try
24             {
25                 int _interval = 5 * 1000;
26                 _timer.Interval = _interval;
27                 _timer.AutoReset = true;
28                 _timer.Enabled = true;
29                 _timer.Elapsed += new System.Timers.ElapsedEventHandler(ActionRun);
30                 Common.WriteLogs("服务已启动");
31             }
32             catch (Exception ex)
33             {
34                 Common.WriteLogs(ex.Message);
35             }
36         }
37         private void ActionRun(object sender, System.Timers.ElapsedEventArgs e)
38         {
39             try
40             {
41                 if (!isRun)
42                 {
43                     HandleService.ActionRun(ref isRun);
44                 }
45             }
46             catch (Exception ex)
47             {
48                 Common.WriteLogs("Error:" + ex.Message);
49             }
50         }
51         protected override void OnStop()
52         {
53             _timer.AutoReset = false;
54             _timer.Enabled = false;
55             _timer.Stop();
56             Common.WriteLogs("服务已停止");
57         }
58     }
59 }
60  

生成项目文件,全部生成成功后,就要开始服务的安装和启动

5.服务的安装和启动
项目成功后,在bin文件夹下找到生成的exe文件和exe.config文件,前者是运行程序,后者是服务的配置信息,实际项目中可以通过更改config中的内容,修改服务的配置信息。
安装和卸载主要使用的是.NET提供的InstallUtil.exe这个文件 ,文件位于C盘对应的目录下 C:\Windows\Microsoft.NET\Framework64\v4.0.30319,拷贝至和exe同一个目录bin下。
 
新建bat文件,用于安装,启动,卸载,停止,重启服务
 
1 安装.bat:
2 sc create MyWinService binPath= "%~dp0WindowsService.exe" start= auto
3 net start MyWinService
4 pause
5  

 

1 启动.bat
2 net start MyWinService
3 pause
4  

 

1 停止.bat
2 net stop MyWinService
3 pause

 

1 卸载.bat
2 net stop MyWinService
3 sc delete MyWinService binPath= "%~dp0JDWindowsService.exe" start= auto
4 pause

 

1 重启.bat
2 net stop MyWinService
3 net start MyWinService
4 pause

 

6.运行安装文件和启动服务
双击“安装.bat”,弹出cmd窗口,如下图,表示安装成功:
 
双击“启动.bat”,如下图表示成功启动服务
 
 
7.查看业务代码的日志写入是否成功
找到项目文件同一个目录下的Log文件,找到日志,如下图所示:
 
可以看到日志文件每隔5秒会写入一条日志文件,至此整个服务运行成功。
 
本文源码下载:
提取码:a62m
 
posted @ 2019-09-22 22:12  y_w_k  阅读(8640)  评论(0编辑  收藏  举报