0

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.

Community
  • 1
  • 1
gzak
  • 3,908
  • 6
  • 33
  • 56
  • Just confirming: you do realise that there is no way to guarantee reliable, atomic execution of most of your user code, right? Even finalizers aren't guaranteed to run if someone unplugs the power cord. With a bit of research you'll likely succeed in handling *most* shutdown scenarios ensuring they leave your system in a predictable state, but the "lights off" case will still need to be handled. – Kirill Shlenskiy Mar 08 '17 at 07:50
  • Task.Delay() [has overloads](https://msdn.microsoft.com/en-us/library/system.threading.tasks.task.delay(v=vs.110).aspx) that take a CancellationToken. Which is the standard way to cancel a task. – Hans Passant Mar 08 '17 at 08:14
  • @Kirill - that's right, I'm aware of the lights off issue - I guess I'm more interested in how to implement clean shutdown in general given a daemon process in .net core (on linux) – gzak Mar 14 '17 at 00:04

0 Answers0