如何准确设置时间段

时间:2014-01-28 06:04:53

标签: c# timer

如果我像这样使用thread.sleep

    while (true)
    {

        File.AppendAllText(strCurrentPath + @"\TimerLog.txt", "begin " + DateTime.Now.ToString() + "\r\n");

        //do some work which will spent time
        spendTime();

        Thread.Sleep(600000);               // sleep  10 mins

    } // while
例如,

首先输出

begin 2014/1/28 12:02:46 

如果线程在10分钟后完全唤醒,那么下一个输出将是

begin 2014/1/28 12:12:46 

但是,因为函数spendTime()会花费一些时间,所以实际输出可能

begin 2014/1/28 12:13:10

我需要的是无论花费时间花费多少时间,线程将在10分钟后完全唤醒,请告诉我如何完成它。

2 个答案:

答案 0 :(得分:2)

while (true)
{
    startTime = Environment.TickCount
    File.AppendAllText(strCurrentPath + @"\TimerLog.txt", "begin " + DateTime.Now.ToString() + "\r\n");

    //do some work which will spent time
    spendTime();

    timeBeforeSleep = Environment.TickCount
    consumedTime = timeBeforeSleep - startTime
    Thread.Sleep(600000 - consumedTime);               // sleep  10 mins

} // while

然而,如果时间比你的时间间隔长,你应该以某种方式处理它。我不知道你想做什么,但你可以像这样跳过睡眠:

if(consumedTime < 600000 )
    Thread.Sleep(600000 - consumedTime);               // sleep  10 mins

答案 1 :(得分:0)

使用Timer而不是Thread.Sleep()

var timer = new Timer(60000); // System.Timers.Timer
timer.Elapsed += (o, a) => spendTime();

顺便说一句,这听起来像是Windows服务的工作。这样你就不用担心程序会退出。

例如,如果您在控制台应用程序中,可以将System.Threading.Timer与TimerCallback一起使用:

using System.Threading;
...

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Starting");

        var timer = new Timer(TimerCallBack, null, 0, 60000); // change 60000 to 6000 for faster testing!
        Console.ReadLine();
    }

    static void TimerCallBack(object o)
    {
        spendTime();
    }

    static void spendTime()
    {
        Console.WriteLine("spent time" + DateTime.Now.ToString());
        return;
    }
}

在任何一种情况下,间隔都会在过去时立即重置,因此您的记录将是准确的(至少降至秒)。

相关问题