I am about to develop a console application that will be required to continually run and carry out work at specific times.
My question is what is are best methods or practices to keep your application alive?
My thought were: A loop that never ends? A timer that sleeps and then jumps to routine when required (after set sleep period)?
I will be compiling the application into an exe and then running it as a service using AlwaysUp.
Regards..
Peter
If your program is going to be continually running then you should sleep until the desired event occurs (e.g. XX seconds passes). If you just spin in a while {} loop you'll suck up CPU times.
If your program is going to always be running on a machine then you should consider making it a service so it automatically starts and stops with the machine.
While you should really be using a service for this, if you need/want to do this anyway, you can use a
ManualResetEvent
to do this:When you're finished 'starting' and want to just wait, you'd then do:
When you want to stop and let it exit, you can then do:
You probably don't want to just spin in a loop needlessly consuming processor time.
Assuming you are on windows, you should have a loop that never ends with a call to WaitForSingleObject() or WaitForMultipleObjects() or MsgWaitForMultipleObjects() depending on your needs. Then have some synchronization object that wakes you up, such as a named event.
See the Win32 Synchronization documentation here. If you elaborate more on what your program needs to do, we can probably provide more specific advice.
A better solution would be to write a console application that does its job and quits. You can then use the Windows Task Scheduler to run it periodically.
Why don't you build your app as a service in the first place?