Scheduler.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Threading;
  5. using Lottomat.Application.Entity.CommonEntity;
  6. using Lottomat.Application.SystemAutoJob.Interface;
  7. using Lottomat.Utils.Date;
  8. namespace Lottomat.Application.SystemAutoJob
  9. {
  10. public class Scheduler
  11. {
  12. private readonly SchedulerConfiguration _configuration = null;
  13. /// <summary>
  14. /// 停止任务时间节点
  15. /// </summary>
  16. private readonly List<int> _hour = new List<int>{ 0, 1, 2, 3, 4, 5 };
  17. //计时器
  18. private static readonly System.Timers.Timer _timer = new System.Timers.Timer();
  19. /// <summary>
  20. /// 构造
  21. /// </summary>
  22. /// <param name="config"></param>
  23. public Scheduler(SchedulerConfiguration config)
  24. {
  25. _configuration = config;
  26. }
  27. /// <summary>
  28. /// 执行任务
  29. /// </summary>
  30. public void Start()
  31. {
  32. _timer.Start();
  33. _timer.Elapsed += new System.Timers.ElapsedEventHandler(ExecuteJob);//到达时间的时候执行事件
  34. _timer.Interval = 0.5 * 60 * 1000; //设置间隔时间,为毫秒
  35. _timer.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件
  36. }
  37. /// <summary>
  38. /// 执行
  39. /// </summary>
  40. private void ExecuteJob(object sender, EventArgs e)
  41. {
  42. DateTime now = DateTimeHelper.Now;
  43. if (!_hour.Contains(now.Hour))
  44. {
  45. List<TaskList> lists = _configuration._taskList;
  46. if (lists.Count != 0)
  47. {
  48. foreach (TaskList list in lists)
  49. {
  50. //执行每一个任务
  51. foreach (ISchedulerJob job in list.Jobs)
  52. {
  53. ThreadStart myThreadDelegate = new ThreadStart(job.Execute);
  54. Thread myThread = new Thread(myThreadDelegate)
  55. {
  56. IsBackground = true
  57. };
  58. myThread.Start();
  59. }
  60. //线程休眠
  61. Thread.Sleep(list.SleepInterval);
  62. }
  63. }
  64. }
  65. }
  66. }
  67. }