DailyRoutinHelper.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. namespace MinicsConsole.Helper;
  2. public class DailyRoutinHelper(ILog log) : IDisposable
  3. {
  4. private Timer? _timer;
  5. private readonly ConcurrentDictionary<string, Func<bool>> _routines = [];
  6. public bool AddorUpdateRoutinWork(string name, Func<bool> action)
  7. {
  8. if (string.IsNullOrEmpty(name) || action is null)
  9. return false;
  10. _routines[name] = action;
  11. return true;
  12. }
  13. public bool StartService(TimeSpan routinTime)
  14. {
  15. this._timer = new(TimerCallback, null, routinTime, routinTime);
  16. return true;
  17. }
  18. void TimerCallback(object? state)
  19. {
  20. Parallel.ForEach(this._routines, routine =>
  21. {
  22. try
  23. {
  24. if (routine.Value?.Invoke() is not true)
  25. {
  26. log.Warning($"Routine Work {routine.Key} Rejected or not success");
  27. }
  28. }
  29. catch
  30. {
  31. log.Error($"Routine Work {routine.Key} Error");
  32. }
  33. });
  34. }
  35. public void Dispose()
  36. {
  37. this._timer?.Dispose();
  38. this._routines.Clear();
  39. }
  40. }