Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Pause Program Execution

Tags:

c#

I am writing a program that will perform an operation every 10 or 15 minutes. I want it to be running all the time, so I need something that is cheap on processing power. What I have read so far seems to suggest that I want to use a Timer. Here is a clip of the code I have so far.

class Program {
    private static Timer timer = new Timer();

    static void Main(string[] args) {
        timer.Elapsed += new ElapsedEventHandler(DoSomething);
        while(true) {
            timer.Interval = TimerMilliseconds(); // The duration of the wait will differ each time
            timer.Enabled=true;
        }
    }
}

The problem here is that the while loop just keeps executing rapidly. How do I halt execution until the timer is elapsed. My program really doesn't need to be multi threaded. Is a Timer the right tool for this job?

Thank you in advance for any help!

UPDATE: Sorry for the confusion. I have implemented the DoSomething method. I just did not include it as I don't believe it is part of my issue.

like image 978
Joe Avatar asked Jan 07 '15 20:01

Joe


3 Answers

Timer's will fire off the Elapsed event once the specified interval has elapsed.

I would do something like this:

private static Timer timer = new Timer();

static void Main(string[] args) 
{
    timer.Elapsed += new ElapsedEventHandler(DoSomething);
    timer.Interval = TimerMilliseconds(); // The duration of the wait will differ each time
    timer.Enabled=true;

    Console.ReadKey(); //Wait for keypress to terminate
}

You could also implement this as a service so you don't have to have a blocking call like Console.ReadKey to keep the program from terminating.

Finally, you could just change the interval in the event handler:

static void DoSomething(...)
{
   timer.Stop();
   timer.Interval = TimerMilliseconds();

   ...
   timer.Start();
}
like image 111
BradleyDotNET Avatar answered Oct 03 '22 04:10

BradleyDotNET


The problem with this code is that you're using a loop to set the Interval and Enabled properties of the Timer, which will execute said assignments over and over - it's not waiting for the timer to execute in some way.

If your application doesn't need to be mutlithreaded, then you might be better simply calling Thread.Sleep between executions.

class Program {    
    static void Main(string[] args) {
        while(true) {
            Thread.sleep(TimerMilliseconds()); // The duration of the wait will differ each time
            DoSomething();
        }
    }
}
like image 44
David Avatar answered Oct 03 '22 03:10

David


take out the timer and loop from your logic. Just use windows scheduler to execute your program after 15 minutes. Or you can use windows services. Please read Best Timer for using in a Windows service

like image 36
ATHER Avatar answered Oct 03 '22 04:10

ATHER