IntervalScheduledTask.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using JLHHJSvr.LJException;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Threading;
  6. namespace JLHHJSvr.Tools
  7. {
  8. public class IntervalScheduledTask
  9. {
  10. public string Name { get; }
  11. public TimeSpan Interval { get; }
  12. public Action TaskAction { get; }
  13. private readonly object _syncRoot = new object();
  14. private Timer _timer;
  15. private bool _running;
  16. public IntervalScheduledTask(string name, TimeSpan interval, Action action)
  17. {
  18. if (interval <= TimeSpan.Zero) throw new LJCommonException("间隔时间必须大于0");
  19. Name = name;
  20. Interval = interval;
  21. TaskAction = action;
  22. _timer = new Timer(_ => Execute(), null, interval, interval);
  23. }
  24. private void Execute()
  25. {
  26. lock (_syncRoot)
  27. {
  28. if (_running) return;
  29. _running = true;
  30. }
  31. try
  32. {
  33. Trace.Write($"{Name}间隔任务执行!!!");
  34. TaskAction.Invoke();
  35. }
  36. catch (Exception ex)
  37. {
  38. Trace.Write(ex);
  39. }
  40. finally
  41. {
  42. lock (_syncRoot)
  43. {
  44. _running = false;
  45. }
  46. }
  47. }
  48. public void Stop() => _timer?.Dispose();
  49. }
  50. public class IntervalSchedulerManager
  51. {
  52. private readonly Dictionary<string, IntervalScheduledTask> _tasks = new Dictionary<string, IntervalScheduledTask>();
  53. public void AddTask(string name, TimeSpan interval, Action action)
  54. {
  55. if (_tasks.ContainsKey(name)) throw new LJCommonException($"任务 \"{name}\" 已存在");
  56. _tasks[name] = new IntervalScheduledTask(name, interval, action);
  57. }
  58. public void RemoveTask(string name)
  59. {
  60. if (_tasks.TryGetValue(name, out var task))
  61. {
  62. task.Stop();
  63. _tasks.Remove(name);
  64. }
  65. }
  66. public void StopAll()
  67. {
  68. foreach (var task in _tasks.Values) task.Stop();
  69. _tasks.Clear();
  70. }
  71. }
  72. }