日期:2014-05-20  浏览次数:20803 次

如何在C#写的WINDOWS服务中,使线程在固定的时间运行?
只存在一个线程,这个线程希望每隔几个小时执行一次,例如每天的1点,5点,9点,13点,17点,21点!
在不论什么时间启动该服务,只要它不在这几个时间上,就不让它运行!!
想问问有没有什么好的方法?
我想到一个是在该线程start之前,先获得当前时间的HOUR,如果不在这几个的话,再一一判断,当前时间距以上以个时间断有多长时间,然后让线程sleep这些时间
不过我觉得这个办法太笨,有没有更好的方法呢?

------解决方案--------------------
Sleep一分钟,醒来的时候看看到点没,没有就继续Sleep一分钟。

没有必要追求极致性能,每一分钟才执行一次操作的程序的开销用户根本感觉不出来。
------解决方案--------------------
感觉 既然是windows服务,如果让它开就自动运行,那系统服务本来就是一直在运行,直接while(true)就可以了. 
不需要什么timer或sleep了.

在start里写

while(true)
{
switch(当前时间)//判断当前时间是否是1点,5点,9点,13点,17点,21点

{
case 1点:
//执行你的代码
//....其他几点类似就行了.
}

}
------解决方案--------------------
如果不要求太精确,可以在线程循环里判断是否在指定的时间前后的一个范围呢,如果不在就每次循环休眠一分钟。
如果要求时间比较精确,休眠的间隔就要比较短,但太短就会占用太多的CPU时间,那么可以用折半逼近指定的时间范围。
------解决方案--------------------
这是我以前写的,希望对你有帮助。
呵呵。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Timers;

namespace TickService
{
public partial class Service1 : ServiceBase
{
Timer timer1;

public Service1()
{
InitializeComponent();
timer1 = new Timer();
//Set the interval of timer to 3 seconds.
timer1.Interval = 3000;
//Enable the timer.
timer1.Enabled = true;
timer1.Elapsed+=new ElapsedEventHandler(timer1_Elapsed);
}

protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.

//Append the text to the sample file.
StreamWriter writer = File.AppendText(@"C:\sample.txt");
writer.WriteLine("Start");
writer.Close();
}

protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
//Append the text Stop to the C:\sample.txt file.
StreamWriter writer = File.AppendText(@"C:\sample.txt");
writer.WriteLine("Stop");
writer.Close();
}

private void timer1_Elapsed(object sender, EventArgs e)
{
//Set the enable property to false.
//timer1.Enabled = false;
//Append the text Tick to the C:\sample.txt file.
StreamWriter writer = File.AppendText(@"C:\sample.txt");
writer.WriteLine("Tick");
writer.Close();
//timer1.Enabled = true;
}
}
}