功能说明:C#创建一个windows服务,服务启动时D:\mcWindowsService.txt写入数据,服务运行期间每隔两秒写入当前时间。
原理这些就不说了,三语两语说不清楚,直接贴一个实例。不能贴图片!!那个压缩文里面是word文档!!有图有真相
1.建立空白项目
2.添加创建windows服务需要的引用,选择System.ServiceProcess。
3.创建服务类,继承ServiceBase,类的源代码在后面。
4.
添加windows服务的安装类。
(1)在类名或者解决方案中新建视图:
(2)上一步后会出来类的视图,右键选择查看设计器:
(3)在设计视图里面添加安装器(有可能会弹出警告框,如图,不用管):
服务创建完成!
安装运行就不用说了吧!!
6
服务类源代码():
C#代码
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Timers;
- namespace SR171
- {
- class Service17: System.ServiceProcess.ServiceBase
- {
- public Service17()//可以自己设定
- {
- this.ServiceName = "MyServiceForShowTime";
- this.CanStop = true;
- this.CanPauseAndContinue = true;
- this.AutoLog = true;
- #region 定时器事件
- Timer aTimer = new Timer(); //System.Timers,不是form的
- aTimer.Elapsed += new ElapsedEventHandler(TimedEvent);
- aTimer.Interval = 2 * 1000; //配置文件中配置的秒数
- aTimer.Enabled = true;
- #endregion
- }
- public static void Main()//必须写
- {
- System.ServiceProcess.ServiceBase.Run(new Service17());
- }
- protected override void OnStart(string[] args)//自己根据要求覆写
- {
- FileStream fs = new FileStream(@"d:\mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write);
- StreamWriter m_streamWriter = new StreamWriter(fs);
- m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
- m_streamWriter.WriteLine("mcWindowsService: Service Started" + DateTime.Now.ToString() + "\n");
- m_streamWriter.Flush();
- m_streamWriter.Close();
- fs.Close();
- }
- protected override void OnStop()
- {
- FileStream fs = new FileStream(@"d:\mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write);
- StreamWriter m_streamWriter = new StreamWriter(fs);
- m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
- m_streamWriter.WriteLine(" mcWindowsService: Service Stopped " + DateTime.Now.ToString() + "\n");
- m_streamWriter.Flush();
- m_streamWriter.Close();
- fs.Close();
- }
- private static void TimedEvent(object source, ElapsedEventArgs e) //运行期间执行
- {
- FileStream fs = new FileStream(@"d:\mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write);
- StreamWriter m_streamWriter = new StreamWriter(fs);
- m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
- m_streamWriter.WriteLine(" Running.11.. " + DateTime.Now.ToString() + "\n");
- m_streamWriter.Flush();
- m_streamWriter.Close();
- fs.Close();
- }
- }
- }
- C_创建windows服务搭配定时器Timer使用实例(用代码做,截图版).rar (462.8
KB)
C#创建windows服务搭配定时器Timer使用实例(用代码做,截图版),布布扣,bubuko.com
时间: 2024-10-11 00:22:52