1

I have a do/while like the following:

do {

  //1.look for a report

  //2.either use interops to run an xl macro report or run a batch file report or run vbs file report

  //3.then sleep/pause program for 150seconds 

} while (look for next report to run)

This is all withing a Console application.

How do I create the 150 second pause/sleep ? Step 2 might involve running various processes and I'm slightly worried that simply using Thread.Sleep might be troublesome as it is not thread safe.


Should I somehow work this sort of code into the structure i.e. put steps 1 and 2 in the CallMeBack method?

static void Main(string[] args) {
    var t = new System.Timers.Timer(1000);
    t.Elapsed += (s, e) => CallMeBack();
    t.Start();

    Console.ReadLine();
}
public static void CallMeBack() {

    //1.look for a report
    //2.either use interops to run an xl macro report or run a batch file report or run vbs file report

    Console.WriteLine("Doing some consuming time work using sleep");
}

(the above is taken from HERE)

Community
  • 1
  • 1
whytheq
  • 34,466
  • 65
  • 172
  • 267
  • 1
    The general approach looks just fine. Note that rather than a `while` loop you'll have an `if(something){timer.Stop();}`. – Servy Nov 20 '12 at 17:53
  • In this implementation the call will happen once every 150 seconds, regardless of how long your operation took. – MrFox Nov 20 '12 at 17:54
  • @Servy ... would you be ok putting your idea as a solution; I could do with seeing the pattern more fully? – whytheq Nov 20 '12 at 17:56
  • 1
    How would sleeping a thread not be thread-safe? Just pause that single thread. Please specify requirements like this beforehand. – MrFox Nov 20 '12 at 17:58

2 Answers2

1

This works in millisecond, you can catch it in case it gets interrupted, but that usually does not happen.

System.Threading.Thread.Sleep(150000);

Edit:

Another option is to use join if you simply want to wait till others are done or if you want to execute once every 150 seconds, your own answer would work. Make sure you know what you want before asking.

If you want thread-safe pause use:

task.Wait(150000);
MrFox
  • 4,852
  • 7
  • 45
  • 81
1

Use a Timer instead of a loop. Steps 1 and 2 would be done inside an event that fires with the interval you specify.

If you need to have a semi-regular timer, you can set the Timer object to not auto-reset and enable it manually at the end of the event instead.

Christoffer
  • 12,712
  • 7
  • 37
  • 53