zoukankan      html  css  js  c++  java
  • 创建Windows服务程序实现定时操作

     在项目开发中,我们可能有这样的需求,就是每隔一段时间,由系统来执行自己预先定义好的一些任务,比如说每隔多久检查一下系统中是否有待发送的邮件,随时监控一些文件的操作等,我们可以通过创建Windows服务程序来实现,关于Windows服务程序的详细介绍请看这篇文章:用Visual C#创建Windows服务程序。看了这篇文章之后,自己动手实践了一下,现在将自己的操作步骤记录如下:

    1.新建Windows项目,选择"Windows服务"类型的工程。

    2.生成的Program.cs文件中,定义了服务启动的Main函数。

    代码
    namespace WindowsService1
    {
    static class Program
    {
    /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    static void Main()
    {
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[]
    {
    new Service1()
    };
    ServiceBase.Run(ServicesToRun);
    }
    }
    }

    3.在新建的工程中,点击Service1.cs文件,切换到代码视图,生成的代码继承于ServiceBase基类,并重载了OnStart和OnStop方法。我在这个文件中进行了一些简单的操作,就是在服务开始的时候,定义一个定时器,然后每隔1秒钟,向文件中写入当前时间。

    代码
    namespace WindowsService1
    {
    public partial class Service1 : ServiceBase
    {
    Timer timer;
    public Service1()
    {
    InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
    timer = new Timer(1000);
    timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
    timer.Start();
    }

    protected override void OnStop()
    {
    timer.Stop();
    timer.Dispose();
    }

    void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
    string filePath = AppDomain.CurrentDomain.BaseDirectory + "test.txt";
    StreamWriter sw = null;
    if (!File.Exists(filePath))
    {
    sw = File.CreateText(filePath);
    }
    else
    {
    sw = File.AppendText(filePath);
    }
    sw.Write("访问时间:"+DateTime.Now.ToString()+Environment.NewLine);
    sw.Close();
    }
    }
    }

    4.向工程中添加一个安装程序类。

    4.在新添加的安装程序类中,设定服务的名称,启动方式,账号名和密码等信息。

    代码
    namespace WindowsService1
    {
    partial class Installer1
    {
    /// <summary>
    /// 必需的设计器变量。
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    private System.ServiceProcess.ServiceProcessInstaller spInstaller;
    private System.ServiceProcess.ServiceInstaller sInstaller;

    /// <summary>
    /// 清理所有正在使用的资源。
    /// </summary>
    /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
    protected override void Dispose(bool disposing)
    {
    if (disposing && (components != null))
    {
    components.Dispose();
    }
    base.Dispose(disposing);
    }

    #region 组件设计器生成的代码

    /// <summary>
    /// 设计器支持所需的方法 - 不要
    /// 使用代码编辑器修改此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {
    components = new System.ComponentModel.Container();

    // 创建ServiceProcessInstaller对象和ServiceInstaller对象
    this.spInstaller =new System.ServiceProcess.ServiceProcessInstaller();
    this.sInstaller = new System.ServiceProcess.ServiceInstaller();

    // 设定ServiceProcessInstaller对象的帐号、用户名和密码等信息
    this.spInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
    this.spInstaller.Password = null;
    this.spInstaller.Username = null;

    // 设定服务的名称
    this.sInstaller.ServiceName = "WindowsService1";

    //设定服务启动的方式
    this.sInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;

    this.Installers.AddRange(new System.Configuration.Install.Installer[] {
    this.spInstaller,this.sInstaller});
    }

    #endregion
    }
    }

    5.生成工程,在bin目录下会生成exe文件。如果直接运行exe文件的话,是不能执行的,需要使用安装Windows服务用到一个名为InstallUtil.exe的命令行工具,打开命令行工具,转到InstallUtil.exe的目录下,我安装的是VS 2010,对应的目录为:C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe,然后执行InstallUtil.exe+待执行的exe文件的目录,如:InstallUtil.exe F:\MyProject\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe。执行成功后,会在Windows的服务中,出现了刚刚添加的服务的名称。

    6.启动该服务,这时打开bin\Debug文件夹,发现已经生成了一个test.txt的文件,里面记录了时间。这说明服务已经正式开始执行。

    7.停止服务的操作也和简单,打开命令行工具,转到C:\Windows\Microsoft.NET\Framework\v4.0.30319目录,然后执行InstallUtil.exe - u F:\MyProject\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe命令就可以了。

    源码下载:创建Windows服务程序

  • 相关阅读:
    蜗牛讲-Fabric入门之架构
    No module named flask 错误解决
    adb测试Doze和App Standby模式
    以太坊挖矿原理
    mac上 go-delve 安装出现The specified item could not be found in the keychain 解决方法
    nginx+lua 根据指定路径反向代理
    asp.net 网站监控方案
    go开源项目influxdb-relay源码分析(一)
    碰到的jpython用ssh连接机器,有些命令无法运行
    git常用命令(备忘)
  • 原文地址:https://www.cnblogs.com/wujy/p/2232045.html
Copyright © 2011-2022 走看看