C# 添加Windows服务,定时任务。

2023-10-30

源码下载地址:http://files.cnblogs.com/files/lanyubaicl/20160830Windows%E6%9C%8D%E5%8A%A1.zip

 

步骤 一 、 创建服务项目。

 

步骤二 、添加安装程序。

 步骤三 、服务属性设置 【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.exe
Net Start ServiceTest
sc 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("微软雅黑", 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;
    }

复制代码

 源码下载地址:http://files.cnblogs.com/files/lanyubaicl/20160830Windows%E6%9C%8D%E5%8A%A1.zip

 

from:

https://www.cnblogs.com/lanyubaicl/p/5825382.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# 添加Windows服务,定时任务。 的相关文章

随机推荐

  • 企业微信消息多久可以撤回?企业微信怎么查看撤回的消息?

    大家都知道 个人微信是可以撤回两分钟以内的消息 超过两分钟就无法撤回了 那企业微信可以撤回发送了多久的消息呢 撤回的消息还能够查看吗 跟着企业微信服务商艾客scrm小编 一起来看看吧 其实 我们使用任何一个聊天工具聊天的过程中 撤回消息在所
  • Unity URP渲染管线与内置渲染管线的性能差别

    首先 我们来了解一下Unity的内置渲染管线 内置渲染管线是Unity较早版本中使用的默认渲染管线 它使用的是传统的图形渲染技术 内置渲染管线提供了一系列的渲染功能 如阴影 反射 抗锯齿等 但是 由于其较为庞大且复杂的设计 它的性能相对较低
  • qt动态显示当前时间如何实现

    Qt qt动态显示当前时间如何实现 vestinfo 1 票 182 include mainwindow h include ui mainwindow h include
  • Java面向对象编程

    第一章 类与对象 面向对象简介 面向过程指的是面对于一个问题的解决方案 更多情况下不会做出重用的设计 面向对象主要设计形式为模块化设计 可以进行重用配置 更多情p况下考虑的是标准 然后根据标准进行拼装 面向对象有三个主要特性 封装性 内部的
  • 【目标检测】Mask RCNN的训练数据集是什么?(含labelimg和labelme的讲解)

    文章目录 一 训练数据集 二 标注工具介绍 2 1 labelimg介绍 2 2 labelme介绍 2 3 两者的对比 三 制作数据案例 在看完何凯明大神的Mask RCNN的时候 突然想到了一个问题 那就是Mask RCNN的训练数据集
  • JAVA-使用Thumbnails压缩图片

    使用Thumbnails压缩图片
  • 休息是不可能休息的

    654 最大二叉树 分析 相比较遍历顺序构建二叉树 这个相对简单 思路 每次找到数组最大值 然后分割数组 class Solution public TreeNode judge vector
  • VersionCode和VersionName的区别

    最近在研究Android4 1的新功能 增量升级 判断客户端apk的版本号和服务器端的版本号在清单文件中VersionCode和VersionName的区别 记录一下 方便自己或者用到的朋友查看 先上结论 Google为APK定义了两个关于
  • 视频场景切换检测(镜头边界检测、镜头分割)

    个人简介 深度学习图像领域工作者 总结链接 链接中主要是个人工作的总结 每个链接都是一些常用demo 代码直接复制运行即可 包括 1 工作中常用深度学习脚本 2 torch numpy等常用函数详解 3 opencv 图片 视频等操作 4
  • 深入探索C++类的const成员函数

    深入探索C 类的const成员函数 const 成员变量的用法和普通 const 变量的用法相似 只需要在声明时加上 const 关键字 初始化 const 成员变量只有一种方法 就是通过构造函数的初始化列表 const 成员函数可以使用类
  • 【Unity】创建一个自己的AR脸部特效安卓程序

    目录 1 创建一个换脸AR场景 2 下载官方提供的BasicFaceFilterAssets资源 3 设置AR面部追踪 4 配置AR Face Manager 5 配置AR Camera为前置摄像头 6 打包并测试 7 添加自己的材质 7
  • oracle 多值更新,oracle 同时更新(update)多个字段多个值

    创建表A B create table A a1 varchar2 33 a2 varchar2 33 a3 varchar2 33 create table B b1 varchar2 33 b2 varchar2 33 b3 varch
  • pytest常用代码示例详细

    test case py usr bin env python3 coding utf 8 File test case py Author sunyajun Creation Time 2023 7 31 9 41 Description
  • C++ 标准库值操作迭代器的常见函数

    迭代器是C 标准库中的重要组件 特别是在容器内部 没有迭代器 容器也就无所谓存在了 例如 vector容器简而言之就是3个迭代器 start finish 以及end of storage vector的任何操作都离不开这3个迭代器 接下来
  • 关于COCO数据集评价参数设置

    在进行DETR like模型的实验过程中 考虑到原模型都是基于COCO数据集上进行的实验 因此博主在实验时也是将其全部都转换为COCO数据集的格式 但这就引发了一个问题 那就是不同的数据集中目标的数目是不同的 而最终结果却有一个不容忽视的指
  • 怎么升级Android Studio版本,Android Studio更新的四种版本介绍

    Android Studio在更新版本时 会有让选择升级源 如下 默认情况下选择的是Stable Channel 这几个Channel的版本是有一些差异的 在Android Studio下载官网上 有如下介绍 Android Studio
  • scrollIntoView() 方法的使用

    在 JavaScript 中 scrollIntoView 方法是用于将指定元素滚动到可见区域内的方法 该方法可以接收一个 options 对象参数 提供了滚动时的一些控制选项 如平滑滚动的行为 下面我们来介绍一个应用 scrollInto
  • tradingview

    文档地址 https b aitrade ga books tradingview index html 初始化 数据对接后的展示图 TV的数据格式 getbars time单位是S 10位数 ms的请除以1000 历史数据回来 塞给get
  • 我的世界进服务器显示C1.8-1.11,我的世界坐标显示(Batty's Coordinates PLUS)Mod

    Batty s Coordinates PLUS最好用的坐标显示Mod是为了你在游戏中方便的显示坐标或者帧数 这样你就不需要频繁的去按F3 并且还内置的定时器的功能 用法 在模式0坐标是隐藏的 模式1 显示了X Y Z坐标 也表明你面对的方
  • C# 添加Windows服务,定时任务。

    源码下载地址 http files cnblogs com files lanyubaicl 20160830Windows E6 9C 8D E5 8A A1 zip 步骤 一 创建服务项目 步骤二 添加安装程序 步骤三 服务属性设置 s