简体   繁体   中英

how to set exactly time period

if i use thread.sleep like this

    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

begin 2014/1/28 12:12:46 

but , because function spendTime() will cost some time , so actual output maybe

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.

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()

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. 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:

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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