简体   繁体   English

如何准确设置时间段

[英]how to set exactly time period

if i use thread.sleep like this 如果我像这样使用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

for example , at first it output 例如,首先它输出

begin 2014/1/28 12:02:46 

if thread exactly wake up after 10 mins , then next output will be 如果线程在10分钟后完全唤醒,那么下一个输出将是

begin 2014/1/28 12:12:46 

but , because function spendTime() will cost some time , so actual output maybe 但是,因为函数spendTime()将花费一些时间,所以实际输出可能

begin 2014/1/28 12:13:10

what i need is no matter how much time spendTime() will cost , thread will exactly wake up after 10 mins , please tell me how to finish it. 我需要的是无论花费时间花费多少时间,线程将在10分钟后完全唤醒,请告诉我如何完成它。

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

However if the while takes longer than your time Interval you should deal with it somehow. 但是,如果时间比你的时间间隔长,你应该以某种方式处理它。 I don't know what you wanna do but you could skip the sleep like this: 我不知道你想做什么,但你可以像这样跳过睡眠:

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

Use a Timer instead of Thread.Sleep() 使用Timer而不是Thread.Sleep()

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

This sounds like a job for a Windows Service, by the way. 顺便说一句,这听起来像是Windows服务的工作。 That way you don't worry about the program exiting. 这样你就不用担心程序退出了。

If you're in a console app, for example, you can use System.Threading.Timer with a TimerCallback: 例如,如果您在控制台应用程序中,则可以将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;
    }
}

In either case, the interval resets immediately as it elapses, so your logging would be accurate (down to the second at least). 在任何一种情况下,间隔都会在过去时立即重置,因此您的记录将是准确的(至少下降到秒)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM