yangl
yangl

Reputation: 337

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.

Upvotes: 0

Views: 278

Answers (2)

Dmitriy Khaykin
Dmitriy Khaykin

Reputation: 5258

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

Upvotes: 0

Silvio Marcovic
Silvio Marcovic

Reputation: 503

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

Upvotes: 2

Related Questions