服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#添加Windows服务 定时任务

C#添加Windows服务 定时任务

2021-12-20 14:35大西瓜3721 C#

这篇文章主要为大家详细介绍了C#添加Windows服务,定时任务的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了c#添加windows服务的具体方法,供大家参考,具体内容如下

源码下载地址:windowsservice1.rar

步骤一、创建服务项目。

C#添加Windows服务 定时任务

步骤二、添加安装程序。

C#添加Windows服务 定时任务

步骤三、服务属性设置 【serviceinstaller1】。

C#添加Windows服务 定时任务

4.1 添加定时任务

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
public partial class sapsyn : servicebase
 {
 system.timers.timer timer1; //计时器
 system.timers.timer timer2; //计时器
 system.timers.timer timer3; //计时器
 system.timers.timer timer4; //计时器
 public sapsyn()
 {
  initializecomponent();
 }
 
 protected override void onstart(string[] args)
 {
  
  timer1 = new system.timers.timer();
  timer1.interval = 8000; //设置计时器事件间隔执行时间
  timer1.elapsed += new system.timers.elapsedeventhandler(tmstart1_elapsed);
  timer1.enabled = true;
 
  timer2 = new system.timers.timer();
  timer2.interval = 8000; //设置计时器事件间隔执行时间
  timer2.elapsed += new system.timers.elapsedeventhandler(tmstart2_elapsed);
  timer2.enabled = true;
 
  timer3 = new system.timers.timer();
  timer3.interval = 8000; //设置计时器事件间隔执行时间
  timer3.elapsed += new system.timers.elapsedeventhandler(tmstart3_elapsed);
  timer3.enabled = true;
 
  timer4 = new system.timers.timer();
  timer4.interval = 8000; //设置计时器事件间隔执行时间
  timer4.elapsed += new system.timers.elapsedeventhandler(tmstart4_elapsed);
  timer4.enabled = true;
 
 }
 
 protected override void onstop() //服务停止执行
 {
  using (system.io.streamwriter sw = new system.io.streamwriter("c:\\log.txt", true))
  {
  sw.writeline(datetime.now.tostring("yyyy-mm-dd hh:mm:ss ") + "stop.");
  }
  this.timer1.enabled = false;
  this.timer2.enabled = false;
  this.timer3.enabled = false
  this.timer4.enabled = false;
 }
 
 
 protected override void onpause()
 {
  //服务暂停执行代码
  base.onpause();
 }
 protected override void oncontinue()
 {
  //服务恢复执行代码
  base.oncontinue();
 }
 protected override void onshutdown()
 {
  //系统即将关闭执行代码
  base.onshutdown();
 }
 
 
 private void tmstart1_elapsed(object sender, system.timers.elapsedeventargs e)
 {
  //执行sql语句或其他操作
  using (system.io.streamwriter sw = new system.io.streamwriter("c:\\" + 1 + "log.txt", true))
  {
  sw.writeline(datetime.now.tostring("yyyy-mm-dd hh:mm:ss ") + "start.");
  }
 }
 private void tmstart2_elapsed(object sender, system.timers.elapsedeventargs e)
 {
  //执行sql语句或其他操作
  using (system.io.streamwriter sw = new system.io.streamwriter("c:\\" + 2 + "log.txt", true))
  {
  sw.writeline(datetime.now.tostring("yyyy-mm-dd hh:mm:ss ") + "start.");
  }
 }
 private void tmstart3_elapsed(object sender, system.timers.elapsedeventargs e)
 {
  //执行sql语句或其他操作
  using (system.io.streamwriter sw = new system.io.streamwriter("c:\\" + 3 + "log.txt", true))
  {
  sw.writeline(datetime.now.tostring("yyyy-mm-dd hh:mm:ss ") + "start.");
  }
 }
 
 private void tmstart4_elapsed(object sender, system.timers.elapsedeventargs e)
 {
  //执行sql语句或其他操作
  using (system.io.streamwriter sw = new system.io.streamwriter("c:\\" + 4 + "log.txt", true))
  {
  sw.writeline(datetime.now.tostring("yyyy-mm-dd hh:mm:ss ") + "start.");
  }
 }
 
 
 
 }

4.2 设置服务启动方式为自动启动

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[runinstaller(true)]
 public partial class projectinstaller : system.configuration.install.installer
 {
 public projectinstaller()
 {
  initializecomponent();
  this.committed += new installeventhandler(projectinstaller_committed);
 }
 private void projectinstaller_committed(object sender, installeventargs e)
 {
  //参数为服务的名字
  system.serviceprocess.servicecontroller controller = new system.serviceprocess.servicecontroller("servicesapsyn");
  controller.start();
 }
 private void serviceinstaller1_afterinstall(object sender, installeventargs e)
 {
 
 }
 }

步骤五、脚本配置。

安装服务脚本

 

复制代码 代码如下:
%systemroot%\microsoft.net\framework\v4.0.30319\installutil.exe windowsservicetest.exenet start servicetestsc config servicetest start= auto

 

卸载服务脚本

 

复制代码 代码如下:
%systemroot%\microsoft.net\framework\v4.0.30319\installutil.exe /u windowsservicetest.exe

 

C#添加Windows服务 定时任务

5.1 停止或启动服务的代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
public partial class form1 : form
 {
 public form1()
 {
  initializecomponent();
 }
 public string thispath = application.startuppath;
 public string propath = "";
 private void form1_load(object sender, eventargs e)
 {
  this.text = "启动服务";
 }
 
 /// <summary>
 /// 启动服务
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void button1_click(object sender, eventargs e)
 {
  cursor = cursors.waitcursor;
  string starpath = @"%systemroot%\microsoft.net\framework\v4.0.30319\installutil.exe " + propath;
 
 
  filestream fs = new filestream(thispath + "\\install.bat", filemode.create);
  streamwriter sw = new streamwriter(fs);
  try
  {
  sw.writeline(starpath);
  sw.writeline("net start servicetest");
  sw.writeline("sc config servicetest start= auto");
  }
  catch (exception ex)
  {
  messagebox.show(ex.message.tostring());
  }
  finally
  {
  sw.close();
  fs.close();
  }
  system.diagnostics.process.start(thispath + "\\install.bat");
  this.text = "启动服务:你选择的服务已经启动。";
  cursor = cursors.default;
 }
 
 /// <summary>
 /// 停止服务
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void button2_click(object sender, eventargs e)
 {
  cursor = cursors.waitcursor;
 
  string starpath = @"%systemroot%\microsoft.net\framework\v4.0.30319\installutil.exe /u " + propath;
 
  filestream fs = new filestream(thispath + "\\uninstall.bat", filemode.create);
  streamwriter sw = new streamwriter(fs);
  try
  {
  sw.writeline(starpath);
  }
  catch (exception ex)
  {
  messagebox.show(ex.message.tostring());
  }
  finally
  {
  sw.close();
  fs.close();
  }
  system.diagnostics.process.start(thispath + "\\uninstall.bat");
  this.text = "启动服务:你选择的服务已经卸载。";
  cursor = cursors.default;
 }
 
 
 
 private void button3_click(object sender, eventargs e)
 {
  ///选择文件框 对象
  openfiledialog ofd = new openfiledialog();
  //打开时指定默认路径
  ofd.initialdirectory = @"c:\documents and settings\administrator.icbcoa-6e96e6be\桌面";
  //如果用户点击确定
  if (ofd.showdialog() == dialogresult.ok)
  {
  //将用户选择的文件路径 显示 在文本框中
  textbox1.text = ofd.filename;
  propath = textbox1.text;
  }
  if (file.exists(thispath + "\\uninstall.bat"))
  {
  file.delete(thispath + "\\uninstall.bat");
  }
  file.create(thispath + "\\uninstall.bat").close();
  if (file.exists(thispath + "\\install.bat"))
  {
  file.delete(thispath + "\\install.bat");
  }
  file.create(thispath + "\\install.bat").close();
 }
 
 
 
 //读写文本 - 写入数据按钮
 private void buttonwrite_click(string filepath)
 {
  
 }
 
 
 /// <summary>
 /// 运行cmd命令
 /// </summary>
 /// <param name="cmd">命令</param>
 /// <returns></returns>
 public static string cmd(string[] cmd)
 {
  process p = new process();
  p.startinfo.filename = "cmd.exe";
  p.startinfo.useshellexecute = false;
  p.startinfo.redirectstandardinput = true;
  p.startinfo.redirectstandardoutput = true;
  p.startinfo.redirectstandarderror = true;
  p.startinfo.createnowindow = true;
  p.start();
  p.standardinput.autoflush = true;
  for (int i = 0; i < cmd.length; i++)
  {
  p.standardinput.writeline(cmd[i].tostring());
  }
  p.standardinput.writeline("exit");
  string strrst = p.standardoutput.readtoend();
  p.waitforexit();
  p.close();
  return strrst;
 }
 
 /// <summary>
 /// 关闭进程
 /// </summary>
 /// <param name="procname">进程名称</param>
 /// <returns></returns>
 public static bool closeprocess(string procname)
 {
  bool result = false;
  system.collections.arraylist proclist = new system.collections.arraylist();
  string tempname = "";
  int begpos;
  int endpos;
  foreach (system.diagnostics.process thisproc in system.diagnostics.process.getprocesses())
  {
  tempname = thisproc.tostring();
  begpos = tempname.indexof("(") + 1;
  endpos = tempname.indexof(")");
  tempname = tempname.substring(begpos, endpos - begpos);
  proclist.add(tempname);
  if (tempname == procname)
  {
   if (!thisproc.closemainwindow())
   thisproc.kill(); // 当发送关闭窗口命令无效时强行结束进程
   result = true;
  }
  }
  return result;
 }
 
 }

5.2 form1.designer.cs 代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
partial class form1
 {
 /// <summary>
 /// 必需的设计器变量。 form1.designer.cs
 /// </summary>
 private system.componentmodel.icontainer components = null;
 
 /// <summary>
 /// 清理所有正在使用的资源。
 /// </summary>
 /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
 protected override void dispose(bool disposing)
 {
  if (disposing && (components != null))
  {
  components.dispose();
  }
  base.dispose(disposing);
 }
 
 #region windows 窗体设计器生成的代码
 
 /// <summary>
 /// 设计器支持所需的方法 - 不要
 /// 使用代码编辑器修改此方法的内容。
 /// </summary>
 private void initializecomponent()
 {
  system.componentmodel.componentresourcemanager resources = new system.componentmodel.componentresourcemanager(typeof(form1));
  this.button1 = new system.windows.forms.button();
  this.button2 = new system.windows.forms.button();
  this.textbox1 = new system.windows.forms.textbox();
  this.button3 = new system.windows.forms.button();
  this.suspendlayout();
  //
  // button1
  //
  this.button1.font = new system.drawing.font("微软雅黑", 12f, system.drawing.fontstyle.regular, system.drawing.graphicsunit.point, ((byte)(134)));
  this.button1.location = new system.drawing.point(12, 90);
  this.button1.name = "button1";
  this.button1.size = new system.drawing.size(134, 60);
  this.button1.tabindex = 0;
  this.button1.text = "启动服务";
  this.button1.usevisualstylebackcolor = true;
  this.button1.click += new system.eventhandler(this.button1_click);
  //
  // button2
  //
  this.button2.font = new system.drawing.font("微软雅黑", 12f, system.drawing.fontstyle.regular, system.drawing.graphicsunit.point, ((byte)(134)));
  this.button2.location = new system.drawing.point(280, 90);
  this.button2.name = "button2";
  this.button2.size = new system.drawing.size(134, 60);
  this.button2.tabindex = 0;
  this.button2.text = "停止服务";
  this.button2.usevisualstylebackcolor = true;
  this.button2.click += new system.eventhandler(this.button2_click);
  //
  // textbox1
  //
  this.textbox1.font = new system.drawing.font("微软雅黑", 10.5f, system.drawing.fontstyle.regular, system.drawing.graphicsunit.point, ((byte)(134)));
  this.textbox1.forecolor = system.drawing.color.maroon;
  this.textbox1.location = new system.drawing.point(108, 13);
  this.textbox1.multiline = true;
  this.textbox1.name = "textbox1";
  this.textbox1.size = new system.drawing.size(306, 67);
  this.textbox1.tabindex = 2;
  //
  // button3
  //
  this.button3.font = new system.drawing.font("微软雅黑", 10.5f, system.drawing.fontstyle.underline, system.drawing.graphicsunit.point, ((byte)(134)));
  this.button3.forecolor = system.drawing.color.blue;
  this.button3.location = new system.drawing.point(12, 12);
  this.button3.name = "button3";
  this.button3.size = new system.drawing.size(90, 68);
  this.button3.tabindex = 3;
  this.button3.text = "请选择服务路径";
  this.button3.usevisualstylebackcolor = true;
  this.button3.click += new system.eventhandler(this.button3_click);
  //
  // form1
  //
  this.autoscaledimensions = new system.drawing.sizef(6f, 12f);
  this.autoscalemode = system.windows.forms.autoscalemode.font;
  this.clientsize = new system.drawing.size(419, 155);
  this.controls.add(this.button3);
  this.controls.add(this.textbox1);
  this.controls.add(this.button2);
  this.controls.add(this.button1);
  this.icon = ((system.drawing.icon)(resources.getobject("$this.icon")));
  this.name = "form1";
  this.text = "选择服务程序";
  this.load += new system.eventhandler(this.form1_load);
  this.resumelayout(false);
  this.performlayout();
 
 }
 
 #endregion
 
 private system.windows.forms.button button1;
 private system.windows.forms.button button2;
 private system.windows.forms.textbox textbox1;
 private system.windows.forms.button button3;
 }

源码下载地址:windowsservice1.rar

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

延伸 · 阅读

精彩推荐
  • C#深入理解C#的数组

    深入理解C#的数组

    本篇文章主要介绍了C#的数组,数组是一种数据结构,详细的介绍了数组的声明和访问等,有兴趣的可以了解一下。...

    佳园9492021-12-10
  • C#VS2012 程序打包部署图文详解

    VS2012 程序打包部署图文详解

    VS2012虽然没有集成打包工具,但它为我们提供了下载的端口,需要我们手动安装一个插件InstallShield。网上有很多第三方的打包工具,但为什么偏要使用微软...

    张信秀7712021-12-15
  • C#SQLite在C#中的安装与操作技巧

    SQLite在C#中的安装与操作技巧

    SQLite,是一款轻型的数据库,用于本地的数据储存。其优点有很多,下面通过本文给大家介绍SQLite在C#中的安装与操作技巧,感兴趣的的朋友参考下吧...

    蓝曈魅11162022-01-20
  • C#C#微信公众号与订阅号接口开发示例代码

    C#微信公众号与订阅号接口开发示例代码

    这篇文章主要介绍了C#微信公众号与订阅号接口开发示例代码,结合实例形式简单分析了C#针对微信接口的调用与处理技巧,需要的朋友可以参考下...

    smartsmile20127762021-11-25
  • C#C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    这篇文章主要介绍了C#设计模式之Strategy策略模式解决007大破密码危机问题,简单描述了策略模式的定义并结合加密解密算法实例分析了C#策略模式的具体使用...

    GhostRider10972022-01-21
  • C#利用C#实现网络爬虫

    利用C#实现网络爬虫

    这篇文章主要介绍了利用C#实现网络爬虫,完整的介绍了C#实现网络爬虫详细过程,感兴趣的小伙伴们可以参考一下...

    C#教程网11852021-11-16
  • C#如何使用C#将Tensorflow训练的.pb文件用在生产环境详解

    如何使用C#将Tensorflow训练的.pb文件用在生产环境详解

    这篇文章主要给大家介绍了关于如何使用C#将Tensorflow训练的.pb文件用在生产环境的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴...

    bbird201811792022-03-05
  • C#三十分钟快速掌握C# 6.0知识点

    三十分钟快速掌握C# 6.0知识点

    这篇文章主要介绍了C# 6.0的相关知识点,文中介绍的非常详细,通过这篇文字可以让大家在三十分钟内快速的掌握C# 6.0,需要的朋友可以参考借鉴,下面来...

    雨夜潇湘8272021-12-28