views:

148

answers:

2

I need to implement a windows service that performs database import, and that once a month. The program receives data via e-mail, and will import them at the end of each month.

Is there a better way than set the program to sleep for max_integer seconds/miliseconds repeatedly ?

+16  A: 

I would not do it as windows service. I would run it as a scheduled task.

Your service will just be sleeping for a month and is just a a waste of resources. Let the OS keep track of the time and start your application to do the once a month processing.

David Basarab
+2  A: 

If you can avoid writing a window service, you'll make your life easier - scheduled tasks may be a better option here. Windows services are best used for things where there is some constant background activity that needs to happen - not for running tasks over long timescales.

However, if you must make this a windows service, then you don't want to set a long-timer sleep timeout. That's most definitely a problematic approach. What happens if your application is restarted? How will it know how long it's been sleeping for? Or what if the thread is restarted?

A better approach is to write a record somewhere in the database that identifies when the next import should happen as a date/time. You windows service can wake up periodically (every few minutes or hours) and see if the current date/time is greater than that value. If it is, run the import and update the next run date in the database to the next time to run.

If your app is restarted, you simply read the value back from the database and continue as before.

LBushkin
What happens if your application is restarted? It reads the last check datetime from the registry, and if the delta from nowtime to registrytime is > interval, performs check, if < interval, sets current interval to (interval-(nowtime-registrytime)), of course first sanity checking whether the clock was set back or not.
Quandary
@user155077: You can certainly do what you're describing, but there's a risk associated there. I would choose to use the database as the storage location for this information, rather than the registry. What would happen if there was a catastrophic server failure and you have to rebuild the machine? There's a good chance that you'll lose that information in the registry. It's a remote possibility - but I've seen it happen. And unfortunately, the system registry is rarely something that gets backed up.
LBushkin