C#添加Windows服务 定时任务

C#添加Windows服务 定时任务,第1张

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

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

源码下载地址:http://xiazai.jb51.net/201701/yuanma/Windowsservice1(jb51.net).rar

步骤一、创建服务项目。

步骤二、添加安装程序。

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

4.1 添加定时任务

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 设置服务启动方式为自动启动

[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

5.1 停止或启动服务的代码

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 代码

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("微软雅黑",((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,((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("微软雅黑",System.Drawing.FontStyle.Underline,((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; }

源码下载地址:http://xiazai.jb51.net/201701/yuanma/Windowsservice1(jb51.net).rar

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的C#添加Windows服务 定时任务全部内容,希望文章能够帮你解决C#添加Windows服务 定时任务所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1256531.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存