2011年6月8日星期三

  用C#编制一个简单的Windows Servcie

 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Configuration;
using System.IO;
 
namespace SMSSender
{
    public partial class SMSSender : ServiceBase
    {
        public SMSSender()
        {
            InitializeComponent();
        }
 
        protected override void OnStart(string[] args)
        {
            // TODO: 在此处添加代码以启动服务。
            Write(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " Start");
        // t是在设计器中添加的一个System.Timers.Timer对象
            this.t.Elapsed += new System.Timers.ElapsedEventHandler(doSomething);
            this.t.Interval = Convert.ToInt32(ConfigurationManager.AppSettings["TimerSleep"]);
            this.t.Start();
        }
 
        protected override void OnStop()
        {
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
            this.t.Stop();
            Write(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " Stop");
        }
 
        // 向指定文件写入指定内容
        protected void Write(string content)
        {
            StreamWriter writer = File.AppendText(@"D:\C\sample.txt");
            writer.WriteLine(content);
            writer.Close();
        }
 
        protected void doSomething(object sender,System.Timers.ElapsedEventArgs e)
        {
            this.t.Stop();
        // 想实现什么功能就在下边做
            Write(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " Sleep for 2sec...");
            System.Threading.Thread.Sleep(2000); // 暂停2秒
            Write(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " Wake Up!");
        // 结束
            this.t.Start();
        }
    }
}

没有评论:

发表评论