一、概要

在工作当中遇到了一个需要定时向客户端推送新闻、文章等内容。这个时候在网上搜了很久没有找到合适的解决方案,其实能解决这个问题的方案有很多比如说用到一些大厂贡献的xxMQ中间件之类的,确实能解决问题。但是目前项目比较小根本用不上这么重的框架,在偶然的看到了一位大佬写的文章提供了一个非常不错的思路本篇文章也是受到他的启发实现了之后这里分享给大家。这个大佬的是58的沈剑文章名称是“1分钟实现延迟消息功能”。

关注本公众号回复“定时推送”即可获得源码地址

原文地址:

二、详细内容

详细内容大概分为4个部分,1.应用场景 2.遇到问题 3.设计 4.实现 5.运行效果

需要定时推送数据,且轻量化的实现。

  • 如果启动一个定时器去定时轮询
  • (1)轮询效率比较低
  • (2)每次扫库,已经被执行过记录,仍然会被扫描(只是不会出现在结果集中),会做重复工作
  • (3)时效性不够好,如果每小时轮询一次,最差的情况下会有时间误差
  • 如何利用“延时消息”,对于每个任务只触发一次,保证效率的同时保证实时性,是今天要讨论的问题。

高效延时消息,包含两个重要的数据结构:

(1)环形队列,例如可以创建一个包含3600个slot的环形队列(本质是个数组)

(2)任务集合,环上每一个slot是一个Set

同时,启动一个timer,这个timer每隔1s,在上述环形队列中移动一格,有一个Current Index指针来标识正在检测的slot。

Task结构中有两个很重要的属性:

(1)Cycle-Num:当Current Index第几圈扫描到这个Slot时,执行任务

(2)Task-Function:需要执行的任务指针

假设当前Current Index指向第一格,当有延时消息到达之后,例如希望3610秒之后,触发一个延时消息任务,只需:

(1)计算这个Task应该放在哪一个slot,现在指向1,3610秒之后,应该是第11格,所以这个Task应该放在第11个slot的Set中

(2)计算这个Task的Cycle-Num,由于环形队列是3600格(每秒移动一格,正好1小时),这个任务是3610秒后执行,所以应该绕3610/3600=1圈之后再执行,于是Cycle-Num=1

Current Index不停的移动,每秒移动到一个新slot,这个slot中对应的Set,每个Task看Cycle-Num是不是0:

(1)如果不是0,说明还需要多移动几圈,将Cycle-Num减1

(2)如果是0,说明马上要执行这个Task了,取出Task-Funciton执行(可以用单独的线程来执行Task),并把这个Task从Set中删除

使用了“延时消息”方案之后,“订单48小时后关闭评价”的需求,只需将在订单关闭时,触发一个48小时之后的延时消息即可:

(1)无需再轮询全部订单,效率高

(2)一个订单,任务只执行一次

(3)时效性好,精确到秒(控制timer移动频率可以控制精度)

首先写一个方案要理清楚自己的项目结构,我做了如下分层。

 

 

Interfaces , 这层里主要约束延迟消息队列的队列和消息任务行。

  1. public interface IRingQueue<T>
  2. {
  3. /// <summary>
  4. /// Add tasks [add tasks will automatically generate: task Id, task slot location, number of task cycles]
  5. /// </summary>
  6. /// <param name="delayTime">The specified task is executed after N seconds.</param>
  7. /// <param name="action">Definitions of callback</param>
  8. void Add(long delayTime,Action<T> action);
  9. /// <summary>
  10. /// Add tasks [add tasks will automatically generate: task Id, task slot location, number of task cycles]
  11. /// </summary>
  12. /// <param name="delayTime">The specified task is executed after N seconds.</param>
  13. /// <param name="action">Definitions of callback.</param>
  14. /// <param name="data">Parameters used in the callback function.</param>
  15. void Add(long delayTime, Action<T> action, T data);
  16. /// <summary>
  17. /// Add tasks [add tasks will automatically generate: task Id, task slot location, number of task cycles]
  18. /// </summary>
  19. /// <param name="delayTime"></param>
  20. /// <param name="action">Definitions of callback</param>
  21. /// <param name="data">Parameters used in the callback function.</param>
  22. /// <param name="id">Task ID, used when deleting tasks.</param>
  23. void Add(long delayTime, Action<T> action, T data, long id);
  24. /// <summary>
  25. /// Remove tasks [need to know: where the task is, which specific task].
  26. /// </summary>
  27. /// <param name="index">Task slot location</param>
  28. /// <param name="id">Task ID, used when deleting tasks.</param>
  29. void Remove(long id);
  30. /// <summary>
  31. /// Launch queue.
  32. /// </summary>
  33. void Start();
  34. }
  35. public interface ITask
  36. {
  37. }

Achieves,这层里实现之前定义的接口,这里写成抽象类是为了后面方便扩展。

  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Linq;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using DelayMessageApp.Interfaces;
  7. namespace DelayMessageApp.Achieves.Base
  8. {
  9. public abstract class BaseQueue<T> : IRingQueue<T>
  10. {
  11. private long _pointer = 0L;
  12. private ConcurrentBag<BaseTask<T>>[] _arraySlot;
  13. private int ArrayMax;
  14. /// <summary>
  15. /// Ring queue.
  16. /// </summary>
  17. public ConcurrentBag<BaseTask<T>>[] ArraySlot
  18. {
  19. get { return _arraySlot ?? (_arraySlot = new ConcurrentBag<BaseTask<T>>[ArrayMax]); }
  20. }
  21. public BaseQueue(int arrayMax)
  22. {
  23. if (arrayMax < 60 && arrayMax % 60 == 0)
  24. throw new Exception("Ring queue length cannot be less than 60 and is a multiple of 60 .");
  25. ArrayMax = arrayMax;
  26. }
  27. public void Add(long delayTime, Action<T> action)
  28. {
  29. Add(delayTime, action, default(T));
  30. }
  31. public void Add(long delayTime,Action<T> action,T data)
  32. {
  33. Add(delayTime, action, data,0);
  34. }
  35. public void Add(long delayTime, Action<T> action, T data,long id)
  36. {
  37. NextSlot(delayTime, out long cycle, out long pointer);
  38. ArraySlot[pointer] = ArraySlot[pointer] ?? (ArraySlot[pointer] = new ConcurrentBag<BaseTask<T>>());
  39. var baseTask = new BaseTask<T>(cycle, action, data,id);
  40. ArraySlot[pointer].Add(baseTask);
  41. }
  42. /// <summary>
  43. /// Remove tasks based on ID.
  44. /// </summary>
  45. /// <param name="id"></param>
  46. public void Remove(long id)
  47. {
  48. try
  49. {
  50. Parallel.ForEach(ArraySlot, (ConcurrentBag<BaseTask<T>> collection, ParallelLoopState state) =>
  51. {
  52. var resulTask = collection.FirstOrDefault(p => p.Id == id);
  53. if (resulTask != null)
  54. {
  55. collection.TryTake(out resulTask);
  56. state.Break();
  57. }
  58. });
  59. }
  60. catch (Exception e)
  61. {
  62. Console.WriteLine(e);
  63. }
  64. }
  65. public void Start()
  66. {
  67. while (true)
  68. {
  69. RightMovePointer();
  70. Thread.Sleep(1000);
  71. Console.WriteLine(DateTime.Now.ToString());
  72. }
  73. }
  74. /// <summary>
  75. /// Calculate the information of the next slot.
  76. /// </summary>
  77. /// <param name="delayTime">Delayed execution time.</param>
  78. /// <param name="cycle">Number of turns.</param>
  79. /// <param name="index">Task location.</param>
  80. private void NextSlot(long delayTime, out long cycle,out long index)
  81. {
  82. try
  83. {
  84. var circle = delayTime / ArrayMax;
  85. var second = delayTime % ArrayMax;
  86. var current_pointer = GetPointer();
  87. var queue_index = 0L;
  88. if (delayTime - ArrayMax > ArrayMax)
  89. {
  90. circle = 1;
  91. }
  92. else if (second > ArrayMax)
  93. {
  94. circle += 1;
  95. }
  96. if (delayTime - circle * ArrayMax < ArrayMax)
  97. {
  98. second = delayTime - circle * ArrayMax;
  99. }
  100. if (current_pointer + delayTime >= ArrayMax)
  101. {
  102. cycle = (int)((current_pointer + delayTime) / ArrayMax);
  103. if (current_pointer + second - ArrayMax < 0)
  104. {
  105. queue_index = current_pointer + second;
  106. }
  107. else if (current_pointer + second - ArrayMax > 0)
  108. {
  109. queue_index = current_pointer + second - ArrayMax;
  110. }
  111. }
  112. else
  113. {
  114. cycle = 0;
  115. queue_index = current_pointer + second;
  116. }
  117. index = queue_index;
  118. }
  119. catch (Exception e)
  120. {
  121. Console.WriteLine(e);
  122. throw;
  123. }
  124. }
  125. /// <summary>
  126. /// Get the current location of the pointer.
  127. /// </summary>
  128. /// <returns></returns>
  129. private long GetPointer()
  130. {
  131. return Interlocked.Read(ref _pointer);
  132. }
  133. /// <summary>
  134. /// Reset pointer position.
  135. /// </summary>
  136. private void ReSetPointer()
  137. {
  138. Interlocked.Exchange(ref _pointer, 0);
  139. }
  140. /// <summary>
  141. /// Pointer moves clockwise.
  142. /// </summary>
  143. private void RightMovePointer()
  144. {
  145. try
  146. {
  147. if (GetPointer() >= ArrayMax - 1)
  148. {
  149. ReSetPointer();
  150. }
  151. else
  152. {
  153. Interlocked.Increment(ref _pointer);
  154. }
  155. var pointer = GetPointer();
  156. var taskCollection = ArraySlot[pointer];
  157. if (taskCollection == null || taskCollection.Count == 0) return;
  158. Parallel.ForEach(taskCollection, (BaseTask<T> task) =>
  159. {
  160. if (task.Cycle > 0)
  161. {
  162. task.SubCycleNumber();
  163. }
  164. if (task.Cycle <= 0)
  165. {
  166. taskCollection.TryTake(out task);
  167. task.TaskAction(task.Data);
  168. }
  169. });
  170. }
  171. catch (Exception e)
  172. {
  173. Console.WriteLine(e);
  174. throw;
  175. }
  176. }
  177. }
  178. }
  179. using System;
  180. using System.Threading;
  181. using DelayMessageApp.Interfaces;
  182. namespace DelayMessageApp.Achieves.Base
  183. {
  184. public class BaseTask<T> : ITask
  185. {
  186. private long _cycle;
  187. private long _id;
  188. private T _data;
  189. public Action<T> TaskAction { get; set; }
  190. public long Cycle
  191. {
  192. get { return Interlocked.Read(ref _cycle); }
  193. set { Interlocked.Exchange(ref _cycle, value); }
  194. }
  195. public long Id
  196. {
  197. get { return _id; }
  198. set { _id = value; }
  199. }
  200. public T Data
  201. {
  202. get { return _data; }
  203. set { _data = value; }
  204. }
  205. public BaseTask(long cycle, Action<T> action, T data,long id)
  206. {
  207. Cycle = cycle;
  208. TaskAction = action;
  209. Data = data;
  210. Id = id;
  211. }
  212. public BaseTask(long cycle, Action<T> action,T data)
  213. {
  214. Cycle = cycle;
  215. TaskAction = action;
  216. Data = data;
  217. }
  218. public BaseTask(long cycle, Action<T> action)
  219. {
  220. Cycle = cycle;
  221. TaskAction = action;
  222. }
  223. public void SubCycleNumber()
  224. {
  225. Interlocked.Decrement(ref _cycle);
  226. }
  227. }
  228. }

Logic,这层主要实现调用逻辑,调用者最终只需要关心把任务放进队列并指定什么时候执行就行了,根本不需要关心其它的任何信息。

  1. public static void Start()
  2. {
  3. //1.Initialize queues of different granularity.
  4. IRingQueue<NewsModel> minuteRingQueue = new MinuteQueue<NewsModel>();
  5. //2.Open thread.
  6. var lstTasks = new List<Task>
  7. {
  8. Task.Factory.StartNew(minuteRingQueue.Start)
  9. };
  10. //3.Add tasks performed in different periods.
  11. minuteRingQueue.Add(5, new Action<NewsModel>((NewsModel newsObj) =>
  12. {
  13. Console.WriteLine(newsObj.News);
  14. }), new NewsModel() { News = "Trump's visit to China!" });
  15. minuteRingQueue.Add(10, new Action<NewsModel>((NewsModel newsObj) =>
  16. {
  17. Console.WriteLine(newsObj.News);
  18. }), new NewsModel() { News = "Putin Pu's visit to China!" });
  19. minuteRingQueue.Add(60, new Action<NewsModel>((NewsModel newsObj) =>
  20. {
  21. Console.WriteLine(newsObj.News);
  22. }), new NewsModel() { News = "Eisenhower's visit to China!" });
  23. minuteRingQueue.Add(120, new Action<NewsModel>((NewsModel newsObj) =>
  24. {
  25. Console.WriteLine(newsObj.News);
  26. }), new NewsModel() { News = "Xi Jinping's visit to the US!" });
  27. //3.Waiting for all tasks to complete is usually not completed. Because there is an infinite loop.
  28. //F5 Run the program and see the effect.
  29. Task.WaitAll(lstTasks.ToArray());
  30. Console.Read();
  31. }

Models,这层就是用来在延迟任务中带入的数据模型类而已了。自己用的时候换成任意自定义类型都可以。

版权声明:本文为justzhuzhu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/justzhuzhu/p/14669109.html