tnblog
首页
视频
资源
登录

C#创建定时服务

6434人阅读 2018/12/13 19:23 总访问:30017 评论:0 收藏:0 手机
分类: c#


       步骤一创建服务项目 

步骤二添加安装程序 

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



4.1 添加定时任务 

  1. public partial class SapSyn : ServiceBase
  2.  {
  3.  System.Timers.Timer timer1; //计时器
  4.  System.Timers.Timer timer2; //计时器
  5.  System.Timers.Timer timer3; //计时器
  6.  System.Timers.Timer timer4; //计时器
  7.  public SapSyn()
  8.  {
  9.   InitializeComponent();
  10.  }
  11.  
  12.  protected override void OnStart(string[] args)
  13.  {
  14.    
  15.   timer1 = new System.Timers.Timer();
  16.   timer1.Interval = 8000//设置计时器事件间隔执行时间
  17.   timer1.Elapsed += new System.Timers.ElapsedEventHandler(TMStart1_Elapsed);
  18.   timer1.Enabled = true;
  19.  
  20.   timer2 = new System.Timers.Timer();
  21.   timer2.Interval = 8000//设置计时器事件间隔执行时间
  22.   timer2.Elapsed += new System.Timers.ElapsedEventHandler(TMStart2_Elapsed);
  23.   timer2.Enabled = true;
  24.  
  25.   timer3 = new System.Timers.Timer();
  26.   timer3.Interval = 8000//设置计时器事件间隔执行时间
  27.   timer3.Elapsed += new System.Timers.ElapsedEventHandler(TMStart3_Elapsed);
  28.   timer3.Enabled = true;
  29.  
  30.   timer4 = new System.Timers.Timer();
  31.   timer4.Interval = 8000//设置计时器事件间隔执行时间
  32.   timer4.Elapsed += new System.Timers.ElapsedEventHandler(TMStart4_Elapsed);
  33.   timer4.Enabled = true;
  34.  
  35.  }
  36.   
  37.  protected override void OnStop(//服务停止执行
  38.  {
  39.   using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\log.txt"true))
  40.   {
  41.   sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Stop.");
  42.   }
  43.   this.timer1.Enabled = false;
  44.   this.timer2.Enabled = false;
  45.   this.timer3.Enabled = false;  
  46.   this.timer4.Enabled = false;
  47.  }
  48.  
  49.  
  50.  protected override void OnPause()
  51.  {
  52.   //服务暂停执行代码
  53.   base.OnPause();
  54.  }
  55.  protected override void OnContinue()
  56.  {
  57.   //服务恢复执行代码
  58.   base.OnContinue();
  59.  }
  60.  protected override void OnShutdown()
  61.  {
  62.   //系统即将关闭执行代码
  63.   base.OnShutdown();
  64.  }
  65.  
  66.   
  67.  private void TMStart1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
  68.  { 
  69.   //执行SQL语句或其他操作
  70.   using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\" + 1 + "log.txt"true))
  71.   {
  72.   sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Start.");
  73.   }
  74.  }
  75.  private void TMStart2_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
  76.  { 
  77.   //执行SQL语句或其他操作
  78.   using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\" + 2 + "log.txt"true))
  79.   {
  80.   sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Start.");
  81.   }
  82.  }
  83.  private void TMStart3_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
  84.  { 
  85.   //执行SQL语句或其他操作
  86.   using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\" + 3 + "log.txt"true))
  87.   {
  88.   sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Start.");
  89.   }
  90.  }
  91.  
  92.  private void TMStart4_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
  93.  { 
  94.   //执行SQL语句或其他操作
  95.   using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\" + 4 + "log.txt"true))
  96.   {
  97.   sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Start.");
  98.   }
  99.  }
  100.  
  101.  
  102.  
  103.  }

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

  1. [RunInstaller(true)]
  2.  public partial class ProjectInstaller : System.Configuration.Install.Installer
  3.  { 
  4.  public ProjectInstaller()
  5.  {
  6.   InitializeComponent();
  7.   this.Committed += new InstallEventHandler(ProjectInstaller_Committed);
  8.  }
  9.  private void ProjectInstaller_Committed(object sender, InstallEventArgs e)
  10.  {
  11.   //参数为服务的名字
  12.   System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController("ServiceSapSyn");
  13.   controller.Start();
  14.  }
  15.  private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
  16.  {
  17.  
  18.  }
  19.  }

步骤五脚本配置 

安装服务脚本

复制代码代码如下:

%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 停止或启动服务的代码 

  1. public partial class Form1 : Form
  2.  {
  3.  public Form1()
  4.  {
  5.   InitializeComponent();
  6.  } 
  7.  public string thispath = Application.StartupPath; 
  8.  public string Propath = ""
  9.  private void Form1_Load(object sender, EventArgs e)
  10.  {
  11.   this.Text = "启动服务";
  12.  }
  13.  
  14.  /// <summary>
  15.  /// 启动服务
  16.  /// </summary>
  17.  /// <param name="sender"></param>
  18.  /// <param name="e"></param>
  19.  private void button1_Click(object sender, EventArgs e)
  20.  {
  21.   Cursor = Cursors.WaitCursor;
  22.   string StarPath = @"%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe " + Propath;
  23.  
  24.  
  25.   FileStream fs = new FileStream(thispath + "\\Install.bat", FileMode.Create);
  26.   StreamWriter sw = new StreamWriter(fs);
  27.   try
  28.   {
  29.   sw.WriteLine(StarPath);
  30.   sw.WriteLine("Net Start ServiceTest");
  31.   sw.WriteLine("sc config ServiceTest start= auto");
  32.   }
  33.   catch (Exception ex)
  34.   {
  35.   MessageBox.Show(ex.Message.ToString());
  36.   }
  37.   finally
  38.   {
  39.   sw.Close();
  40.   fs.Close();
  41.   }
  42.   System.Diagnostics.Process.Start(thispath + "\\Install.bat");
  43.   this.Text = "启动服务:你选择的服务已经启动。";
  44.   Cursor = Cursors.Default;
  45.  }
  46.  
  47.  /// <summary>
  48.  /// 停止服务
  49.  /// </summary>
  50.  /// <param name="sender"></param>
  51.  /// <param name="e"></param>
  52.  private void button2_Click(object sender, EventArgs e)
  53.  {
  54.   Cursor = Cursors.WaitCursor;
  55.  
  56.   string StarPath = @"%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u " + Propath;
  57.  
  58.   FileStream fs = new FileStream(thispath + "\\Uninstall.bat", FileMode.Create);
  59.   StreamWriter sw = new StreamWriter(fs);
  60.   try
  61.   {
  62.   sw.WriteLine(StarPath); 
  63.   }
  64.   catch (Exception ex)
  65.   {
  66.   MessageBox.Show(ex.Message.ToString());
  67.   }
  68.   finally
  69.   {
  70.   sw.Close();
  71.   fs.Close();
  72.   }
  73.   System.Diagnostics.Process.Start(thispath + "\\Uninstall.bat");
  74.   this.Text = "启动服务:你选择的服务已经卸载。";
  75.   Cursor = Cursors.Default;
  76.  }
  77.  
  78.   
  79.  
  80.  private void button3_Click(object sender, EventArgs e)
  81.  {
  82.   ///选择文件框 对象
  83.   OpenFileDialog ofd = new OpenFileDialog();
  84.   //打开时指定默认路径
  85.   ofd.InitialDirectory = @"C:\Documents and Settings\Administrator.ICBCOA-6E96E6BE\桌面";
  86.   //如果用户点击确定
  87.   if (ofd.ShowDialog() == DialogResult.OK)
  88.   {
  89.   //将用户选择的文件路径 显示 在文本框中
  90.   textBox1.Text = ofd.FileName;
  91.   Propath = textBox1.Text;
  92.   }
  93.   if (File.Exists(thispath + "\\Uninstall.bat"))
  94.   {
  95.   File.Delete(thispath + "\\Uninstall.bat");
  96.   }
  97.   File.Create(thispath + "\\Uninstall.bat").Close();
  98.   if (File.Exists(thispath + "\\Install.bat"))
  99.   {
  100.   File.Delete(thispath + "\\Install.bat");
  101.   }
  102.   File.Create(thispath + "\\Install.bat").Close();
  103.  }
  104.  
  105.   
  106.  
  107.  //读写文本 - 写入数据按钮
  108.  private void buttonWrite_Click(string filePath)
  109.  { 
  110.    
  111.  }
  112.  
  113.  
  114.  /// <summary>
  115.  /// 运行CMD命令
  116.  /// </summary>
  117.  /// <param name="cmd">命令</param>
  118.  /// <returns></returns>
  119.  public static string Cmd(string[] cmd)
  120.  {
  121.   Process p = new Process();
  122.   p.StartInfo.FileName = "cmd.exe";
  123.   p.StartInfo.UseShellExecute = false;
  124.   p.StartInfo.RedirectStandardInput = true;
  125.   p.StartInfo.RedirectStandardOutput = true;
  126.   p.StartInfo.RedirectStandardError = true;
  127.   p.StartInfo.CreateNoWindow = true;
  128.   p.Start();
  129.   p.StandardInput.AutoFlush = true;
  130.   for (int i = 0; i < cmd.Length; i++)
  131.   {
  132.   p.StandardInput.WriteLine(cmd[i].ToString());
  133.   }
  134.   p.StandardInput.WriteLine("exit");
  135.   string strRst = p.StandardOutput.ReadToEnd();
  136.   p.WaitForExit();
  137.   p.Close();
  138.   return strRst;
  139.  }
  140.  
  141.  /// <summary>
  142.  /// 关闭进程
  143.  /// </summary>
  144.  /// <param name="ProcName">进程名称</param>
  145.  /// <returns></returns>
  146.  public static bool CloseProcess(string ProcName)
  147.  {
  148.   bool result = false;
  149.   System.Collections.ArrayList procList = new System.Collections.ArrayList();
  150.   string tempName = "";
  151.   int begpos;
  152.   int endpos;
  153.   foreach (System.Diagnostics.Process thisProc in System.Diagnostics.Process.GetProcesses())
  154.   {
  155.   tempName = thisProc.ToString();
  156.   begpos = tempName.IndexOf("(") + 1;
  157.   endpos = tempName.IndexOf(")");
  158.   tempName = tempName.Substring(begpos, endpos - begpos);
  159.   procList.Add(tempName);
  160.   if (tempName == ProcName)
  161.   {
  162.    if (!thisProc.CloseMainWindow())
  163.    thisProc.Kill(); // 当发送关闭窗口命令无效时强行结束进程
  164.    result = true;
  165.   }
  166.   }
  167.   return result;
  168.  }
  169.  
  170.  }

注意:调用cmd命令,不认空格,有空格必报错


5.2 Form1.Designer.cs 代码 (一般自动生成):

  1. partial class Form1
  2.  {
  3.  /// <summary>
  4.  /// 必需的设计器变量。 Form1.Designer.cs
  5.  /// </summary>
  6.  private System.ComponentModel.IContainer components = null;
  7.  
  8.  /// <summary>
  9.  /// 清理所有正在使用的资源。
  10.  /// </summary>
  11.  /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
  12.  protected override void Dispose(bool disposing)
  13.  {
  14.   if (disposing && (components != null))
  15.   {
  16.   components.Dispose();
  17.   }
  18.   base.Dispose(disposing);
  19.  }
  20.  
  21.  #region Windows 窗体设计器生成的代码
  22.  
  23.  /// <summary>
  24.  /// 设计器支持所需的方法 - 不要
  25.  /// 使用代码编辑器修改此方法的内容。
  26.  /// </summary>
  27.  private void InitializeComponent()
  28.  {
  29.   System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
  30.   this.button1 = new System.Windows.Forms.Button();
  31.   this.button2 = new System.Windows.Forms.Button();
  32.   this.textBox1 = new System.Windows.Forms.TextBox();
  33.   this.button3 = new System.Windows.Forms.Button();
  34.   this.SuspendLayout();
  35.   // 
  36.   // button1
  37.   // 
  38.   this.button1.Font = new System.Drawing.Font("微软雅黑"12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
  39.   this.button1.Location = new System.Drawing.Point(1290);
  40.   this.button1.Name = "button1";
  41.   this.button1.Size = new System.Drawing.Size(13460);
  42.   this.button1.TabIndex = 0;
  43.   this.button1.Text = "启动服务";
  44.   this.button1.UseVisualStyleBackColor = true;
  45.   this.button1.Click += new System.EventHandler(this.button1_Click);
  46.   // 
  47.   // button2
  48.   // 
  49.   this.button2.Font = new System.Drawing.Font("微软雅黑"12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
  50.   this.button2.Location = new System.Drawing.Point(28090);
  51.   this.button2.Name = "button2";
  52.   this.button2.Size = new System.Drawing.Size(13460);
  53.   this.button2.TabIndex = 0;
  54.   this.button2.Text = "停止服务";
  55.   this.button2.UseVisualStyleBackColor = true;
  56.   this.button2.Click += new System.EventHandler(this.button2_Click);
  57.   // 
  58.   // textBox1
  59.   // 
  60.   this.textBox1.Font = new System.Drawing.Font("微软雅黑"10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
  61.   this.textBox1.ForeColor = System.Drawing.Color.Maroon;
  62.   this.textBox1.Location = new System.Drawing.Point(10813);
  63.   this.textBox1.Multiline = true;
  64.   this.textBox1.Name = "textBox1";
  65.   this.textBox1.Size = new System.Drawing.Size(30667);
  66.   this.textBox1.TabIndex = 2;
  67.   // 
  68.   // button3
  69.   // 
  70.   this.button3.Font = new System.Drawing.Font("微软雅黑"10.5F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
  71.   this.button3.ForeColor = System.Drawing.Color.Blue;
  72.   this.button3.Location = new System.Drawing.Point(1212);
  73.   this.button3.Name = "button3";
  74.   this.button3.Size = new System.Drawing.Size(9068);
  75.   this.button3.TabIndex = 3;
  76.   this.button3.Text = "请选择服务路径";
  77.   this.button3.UseVisualStyleBackColor = true;
  78.   this.button3.Click += new System.EventHandler(this.button3_Click);
  79.   // 
  80.   // Form1
  81.   // 
  82.   this.AutoScaleDimensions = new System.Drawing.SizeF(6F12F);
  83.   this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  84.   this.ClientSize = new System.Drawing.Size(419155);
  85.   this.Controls.Add(this.button3);
  86.   this.Controls.Add(this.textBox1);
  87.   this.Controls.Add(this.button2);
  88.   this.Controls.Add(this.button1);
  89.   this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
  90.   this.Name = "Form1";
  91.   this.Text = "选择服务程序";
  92.   this.Load += new System.EventHandler(this.Form1_Load);
  93.   this.ResumeLayout(false);
  94.   this.PerformLayout();
  95.  
  96.  }
  97.  
  98.  #endregion
  99.  
  100.  private System.Windows.Forms.Button button1;
  101.  private System.Windows.Forms.Button button2;
  102.  private System.Windows.Forms.TextBox textBox1;
  103.  private System.Windows.Forms.Button button3;
  104.  }



注意:调用cmd命令,不认空格,有空格必报错

评价

Css弹性盒子,flex布局

css弹性盒子由于版本不同浏览器问题造成了一些不同的写法display:flexbox;在google浏览器中如果使用下面的写法就不行displa...

Css图片和文字对齐问题

文字和图片写到一排经常会出现对不齐的问题 这样感觉图片会上来一点没有和文字对齐,如下图 但是如果修改下html结...

GitHub 上传项目

补充简化方法:登录git创建项目--&gt;拉取刚刚创建的项目--&gt;复制需要的代码进去--&gt;上传提交即可先拉取项目在上传代码...

NET Core 使用 EF Code First

下面这些内容很老了看这篇:https://www.tnblog.net/aojiancc2/article/details/5365 项目使用多层,把数据库访问...

Windows平台分布式架构实践 - 负载均衡

原文地址: https://www.cnblogs.com/atree/p/windows_loadbalancer.html 概述  最近.NET的世界开始闹腾了,微软官方终...

Css实现简单矩形对话框

在前端做项目时,我们可能会遇到写对话框的需求,这次做视频会议页面就遇到了,记录下日后有个参照。//网页部分 &lt;divcla...

CAPS.NET 保存base64位格式的图片

publicvoidUpload() { //取出图片对应的base64位字符 stringimgBase=Request[&quot;imgBase&quot;]; //c#里边的base6...

使用OLEDB读取不同版本ExCel的连接字符串设置

使用OleBD读取excel的时候,excel不同的版本,连接字符串的写法也会不一样。///&lt;summary&gt; ///读取excel ///&lt;/su...

vs2017 对 COM 组件的调用返回了错误 HRESULT E_FAIL

vs2017添加引用报错 对 COM 组件的调用返回了错误 HRESULT E_FAIL 1.以管理员身份打开vs2017开发人员命令指示符 2...

分布式服务架构与微服务架构概念的区别与联系

分布式:分散压力。微服务:分散能力。当下理解分布式:不同模块部署在不同服务器上作用:分布式解决网站高并发带来问题集...

分布式-微服务-集群的区别

1.分布式将一个大的系统划分为多个业务模块,业务模块分别部署到不同的机器上,各个业务模块之间通过接口进行数据交互。区...

NPOI操作exCel 2007/2010版本

HSSFWorkbook:是操作Excel2003以前(包括2003)的版本,扩展名是.xlsXSSFWorkbook:是操作Excel2007的版本,扩展名是.xlsx先...

这样学英语三个月超过你过去学三年

本文作者三年间从四级勉强及格到高级口译笔试210,口试232。找工作面试时给其口试的老外考官听了一分钟就说你的英语不用考...

EasyUI弹窗批量修改Combogrid下拉框的值

JS方法//点击弹出批量修改框 UpdateLot:function(){ varrow=$(&quot;#dg&quot;).datagrid(&quot;getChecked&quot;); if(...

js与Controller中分割字符串的方法

js: varstr=OpenRule; varstrs=newArray(); strs=str.split(&quot;,&quot;); for(vari=0;i&lt;strs.length;i++){ $(&q...

如何修改CSS中存在的element.style内联样式

改腾讯地图的时候调整了下样式,发现样式一直存在问题,修改style里面的值,一点用都没有,html中这个值还找不到是在哪里出...
不需要签名
排名
56
文章
8
粉丝
0
评论
1
Oracle中MERGE INTO,for,start with,decode用法
剑轩 : 多来一点点解释就更好了
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术
欺骗的友谊是痛苦的创伤,虚伪的同情是锐利的毒箭。