I have a routine that I need to execute every second, with low accumulated time errors (in 1 hour should fire 3600 times). The routine takes a varying 100 to 300ms (roughly) to exectue.
What is the most reasonable approach? Using “sleep” , timers, systemclocks or other means?
Are there any descriptive tutorials on the timers?
hmmm. the link doesn’t offer a lot of explanation:
public static void Main()
{
Timer MyTimer =
new Timer(new TimerCallback(RunMe), null, 5000, 1000);
Debug.Print(
"The timer will fire in 5 seconds and then fire priodically every 1 second");
Thread.Sleep(Timeout.Infinite);
Does this last line cause the main to stop? I certainly don’t want that…it has to be running always to handle reading keys, doing other things. But I do want another thing (slow /lengthy) routine to happen once a second.
[quote]Then the code that read keys and does other things should be done in the loop. In the main function or on another thread.
[/quote]
So basically don’t put this example in main, make it into its own timer thread that can be set to Sleep(Timeout.Infinite); Then main can carry on its merry way doing its normal functions like reading the keys.
I’ll give it a try!
Once you start a timer it will fire a tick event forever until you explicitly stop the timer. You don’t need Sleep(Timeout.Infinite) in the tick event handler. You will still need Sleep(Timeout.Infinite) as the last line of main() or your program will end as Architect described.
That structure works fine if you’re not on a Gadgeteer platform and using the ProgramStarted construct. In fact, if you use say the Panda or similar template, you get exactly that.
As long as you have some Thread.Sleep(x) (where x is any value) within your loop then that is fine. If you don’t Sleep() in there somewhere then you’ll have too tight a loop and your debugger will never get a chance to respond. You may have problems getting timer events to fire on time as well.