0

I need to call a function at a specific time during a day. There are other examples in the internet using, Timer etc. But I am wondering, why not simply have a thread which calls a method having a while loop.

            while (true)
            {
                if (DateTime.Now.TimeOfDay == new TimeSpan(0, 0, 0))
                {
                    ManualTaskProcession();
                }
            }

This will be run on a separate thread - wondering why this approach is not mentioned anywhere, or is it correct?

P.S This is inside a Windows Service.

Paul Alwin
  • 181
  • 1
  • 2
  • 12
  • 2
    use something like Hangfire - [link](https://www.hangfire.io) where you can setup a job to run at a set time period. – Ben D Dec 18 '18 at 16:22
  • That's an awfully tight loop. It will spin and spin like that forever, sucking up CPU execute resources. A better way would be to do an async `await Task.Delay(someAmountOfTime)` and then do the test. I'm sure if you checked every minute, you'd be pretty close. – Flydog57 Dec 18 '18 at 16:23
  • 2
    why not just create a scheduled task and have it execute / launch your application – MethodMan Dec 18 '18 at 16:23
  • Thanks Guys. MethodMan - The windows service does many other things, this is just one of the sub tasks this performs, so for me it did not make sense to have another schedular launch this in intervals (tell me if you feel otherwise) @Flydog57 - Ah yes thanks makes sense, as before I had the logic for this method to run every 24 hours, with thread sleep - but that does not garuntee the time when it will run (any 24 hour span). So, you are suggesting - Delay of 1 minute and checking say its midnight? And that will be better than what I am doing (i hope)? – Paul Alwin Dec 18 '18 at 16:29
  • 1
    BTW, Hangfire is great. But yes, figure out how much slop you can handle around midnight and wait that long. If you only ever want to run at midnight, you could start by waiting 18 hours (right after midnight) and then 3/4 (or some other large fraction) of the time between now and midnight. Only when you get close, wait 30 or 60 seconds. But, really, take a look at Hangfire; if I remember right, it's something you NuGet into your code. – Flydog57 Dec 18 '18 at 16:37

0 Answers0