Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build a very-low resolution timer?

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 ?

like image 236
Stefan Steiger Avatar asked Dec 01 '22 11:12

Stefan Steiger


2 Answers

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.

like image 181
David Basarab Avatar answered Dec 04 '22 23:12

David Basarab


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.

like image 33
LBushkin Avatar answered Dec 05 '22 01:12

LBushkin