• 学写Windows Service


    记得很早之前,一个同事要写一个定时任务,先要在一条新闻在到达设定期限时 由程序自动删除

    可以一直没有思路 问我 我也没有好的办法

    后来,我在前段时间找到一个 方法:http://www.cnblogs.com/ucetgg/archive/2009/02/11/1388481.html

    也不太好,也有个高人回复了 给我指明了思路,用Windows Service ,可我没有写过

    后来 看到一篇文章:http://www.cnblogs.com/lovecherry/archive/2005/03/25/125527.html

    用Windows Service 作为关键词 搜了搜博客园 有很多人已经做过

    步骤我就不详细说了 ,帖我的代码出来吧:

    Code
    namespace WindowsService
    {
        
    public partial class Service1 : ServiceBase
        {
            
    public Service1()
            {
                InitializeComponent();
            }

            
    /// <summary>
            
    /// 开始
            
    /// </summary>
            
    /// <param name="args"></param>
            protected override void OnStart(string[] args)
            {
                
    //Thread t = new Thread(new ThreadStart(Run));
                
    //t.Start();
                timer1.Enabled = true;
                execTask();
                
            }

            
    /// <summary>
            
    /// 结束
            
    /// </summary>
            protected override void OnStop()
            {
                timer1.Enabled 
    = false;
            }

            
    private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                Thread t 
    = new Thread(new ThreadStart(execTask));
                t.Start();
            }
            
    /// <summary>
            
    /// 执行任务
            
    /// </summary>
            private void execTask()
            {
                
    string strSql = "insert into WebSite_CMSContent (Title,body) values('tt','xx')";
                DbHelperSQL.ExecuteSql(strSql);
            }
        }
    }

    注意:

    1.Timer控件 一定要是 System.Timers.Timer 类型

    2. InstallUtil.exe 一定要对应framework 的版本,比如f ramework 2.0的程序 1.1版本下的InstallUtil工具就不行

    3.默认情况下 服务是不自动启动的,需要安装成功后手动 启动

  • 相关阅读:
    LintCode "Subarray Sum II"
    LintCode "Maximum Subarray Difference"
    LeetCode "Flip Game II"
    LintCode "Sliding Window Median" & "Data Stream Median"
    LintCode "Permutation Index"
    LintCode "Count of Smaller Number before itself"
    LeetCode "Nim Game"
    Etcd在Linux CentOS7下载、安装
    CentOS7 查看开启端口
    CentOS7-防火墙firewall 状态、重启、关闭
  • 原文地址:https://www.cnblogs.com/ucetgg/p/1431176.html
Copyright © 2020-2023  润新知