C# 定时功能
有时候会受到这样一种需求:时间点A到时间点B上线,然后休息时间段C,然后时间点D到时间点E又上线,然后又休息一个时间段。
乍一看,有点乱,其实只要用定时就ok了,既然要实现定时,那就肯定要用到Timer这个控件,timer可以实现定时,每隔一段时间就会执行一次,然后判断当前时间是否符合要求,执行具体的判断逻辑,虽然很乱,但是只是实现的逻辑乱而已,而用的只是每隔一段时间就执行某程序就ok了。
实现定时功能,要是想简单点,直接来个button就得了,要是想复杂,稳定点,那就做个Windows服务。
下面看简单点的button,只要不关闭,就会一直执行下去。
private void button1_Click(object sender, EventArgs e) { System.Timers.Timer timer = new System.Timers.Timer(); timer.Interval = 5 * 60 * 1000; timer.Elapsed += new System.Timers.ElapsedEventHandler(DoTaskTimer); timer.Start(); } private void DoTaskTimer(object sender, System.Timers.ElapsedEventArgs e) { using (StreamWriter sw = new StreamWriter(@"E:\file\1.txt", true, Encoding.UTF8)) { sw.WriteLine(e.SignalTime.ToString()); } }
Windows服务===================================================================
新建一个Windows服务的项目
在 Service1的设计窗口里 右键 添加 安装程序,会自动为我们生成一个类

设置 serviceInstaller1的属性

设置serviceProcessInstaller1的属性

开始coding
public partial class Service1 : ServiceBase { System.Timers.Timer timer; public Service1() { InitializeComponent(); timer = new System.Timers.Timer(); timer.Interval = 2 * 1000; timer.Elapsed += new System.Timers.ElapsedEventHandler(myService); } protected override void OnStart(string[] args) { timer.Start(); } protected override void OnStop() { timer.Stop(); } private void myService(object sender, System.Timers.ElapsedEventArgs e) { string path = @"E:\file"; if(!Directory.Exists(path)) { Directory.CreateDirectory(path); } using (StreamWriter sw = new StreamWriter(path+"/2.txt", true, Encoding.UTF8)) { sw.WriteLine(e.SignalTime.ToString()); } } }
安装服务+++++++++++++++++++++++++++++++++++++++++++++++++++++++
以管理员身份运行,然后
输入 cd C:\Windows\Microsoft.NET\Framework\v4.0.30319 回车
切换当前目录,此处需要注意的是,在C:\Windows\Microsoft.NET\Framework目录下有很多类似版本,具体去哪个目录要看项目的运行环境,例 如果是.net framework2.0则需要输入 cd C:\Windows\Microsoft.NET\Framework\v2.0.50727
再输入 InstallUtil.exe 你的exe路径 回车就ok了。

然后打开服务管理器,查看

浙公网安备 33010602011771号