自动执行服务程序 两法
创建服务程序,利用此程序完成自动执行的工作。两种方法:首先创建服务程序,下图
http://dl.iteye.com/upload/attachment/328349/d404c2e1-27e9-3ebd-9742-7bd5fc775b74.png
一、timer法
添加timer控件,据说工具箱中已有的timer(System.Windows.Forms)不能执行此类程序,必须添加新的timer控件(system.Timers)。这两个Timer控件的命名空间不同。
http://dl.iteye.com/upload/attachment/328351/21d04983-14a2-3696-b78a-5e89939c2042.png
http://dl.iteye.com/upload/attachment/328353/4ecf2933-20e5-3352-9a1a-fcb6dc348704.png
拖曳控件到设计页面右键设置属性如执行间隔等。双击添加事件执行以下测试代码
//Timer方法 private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { int a = 0; String s = System.DateTime.Now.ToString(); if (!File.Exists("D:\\bbbirdlog.txt")) { StreamWriter sr = File.CreateText("D:\\bbbirdlog.txt"); sr.WriteLine("-------------------------START SRV---------------------"); sr.WriteLine("现在Timer方法时间:{0}", s); sr.Close(); } else { StreamWriter sr = File.AppendText("D:\\bbbirdlog.txt"); sr.WriteLine("-------------------------START SRV---------------------"); sr.WriteLine("现在Timer方法时间:{0}时间开始", s); sr.Close(); } StreamWriter sr2 = File.AppendText("D:\\bbbirdlog.txt"); sr2.WriteLine("-------------------------START SRV---------------------"); sr2.WriteLine("Timer方法循环{0}次", a++); sr2.Close(); }
二、线程法
http://dl.iteye.com/upload/attachment/328355/0378dbf0-127d-3787-ae88-5d94052aa6d7.png
http://dl.iteye.com/upload/attachment/328357/634a1ed7-c156-3843-b951-7f1ff06d8b3a.png
http://dl.iteye.com/upload/attachment/328359/24017637-33fb-39ed-a073-4a07a8149754.png
// 时间扫描间隔 private static int timeSpan = 3000; private Thread thMoniTask;//用来监测执行进度的线程 public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { //启动线程 thMoniTask = new Thread(new ThreadStart(MyProc)); thMoniTask.Start(); } protected override void OnStop() { } //线程法 private void MyProc() { int a = 0; while (true) { String s = System.DateTime.Now.ToString(); if (!File.Exists("D:\\bbbirdlog.txt")) { StreamWriter sr = File.CreateText("D:\\bbbirdlog.txt"); sr.WriteLine("-------------------------START SRV---------------------"); sr.WriteLine("现在线程法时间:{0}", s); sr.Close(); } else { StreamWriter sr = File.AppendText("D:\\bbbirdlog.txt"); sr.WriteLine("-------------------------START SRV---------------------"); sr.WriteLine("现在线程法时间:{0}时间开始", s); sr.Close(); } // 扫描间隔 Thread.Sleep(timeSpan); StreamWriter sr2 = File.AppendText("D:\\bbbirdlog.txt"); sr2.WriteLine("-------------------------START SRV---------------------"); sr2.WriteLine("线程法循环{0}次", a++); sr2.Close(); } }
启动或安装:
http://dl.iteye.com/upload/attachment/328361/5b30e73a-6fa7-3ed7-a13d-21a6a1b9f17f.png
http://dl.iteye.com/upload/attachment/328365/67186b05-0dc2-3dc3-9d20-ade256643696.png
服务启动设置:
如果无法启动服务,请将项目文件夹赋予权限如everyone则可以启动
http://dl.iteye.com/upload/attachment/328369/81ab5b96-1fd8-3209-bb30-4a85bcaf174d.png
运行效果:
http://dl.iteye.com/upload/attachment/328367/180626de-2d74-35fb-9c92-96ddf65954c7.png
附:源代码
http://dl.iteye.com/topics/download/33cc726e-57d5-3d1d-887e-f9cbe7c76f2a
页:
[1]