I'm trying to write a daemon app using .NET Core (whether I also use ASP.NET Core is still TBD), and I intend to run this app on linux. The daemon process will essentially be a chron job, and my plan is to implement it as a Task
that contains an infinite while
loop, and in each iteration it does await Task.Delay(...)
to "sleep" between intervals. I'm aware that I can also use a Timer
or similar, but in my case each iteration can take a long time, and the duration is quite variable, so rather than run on a strictly fixed cadence, I'd prefer to run on a variable schedule such that the time between iterations is fixed.
Anyway, I don't think that's relevant to the question. The real question is: how can I implement a graceful shutdown of this daemon thread, such that it only shuts down in between iterations while awaiting the delay? One idea was to make the thread a foreground thread and handle cancellations at the delay step, I'm not sure how to do that (or even if that's a thing on linux - I read somewhere that bg/fg threads are a Windows concept).
Sample code would be a plus.