最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

如何實現定時推送的具體方案

 更新時間:2021年04月19日 17:33:40   作者:dotNet源計劃  
在工作當中遇到了一個需要定時向客戶端推送新聞、文章等內容。小項目又用不了大框架,這個時候在網上搜了很久沒有找到合適的解決方案,直到看到了一位大佬寫的文章提供了一個非常不錯的思路本篇文章也是受到他的啟發(fā)實現了之后這里分享給大家

詳細內容

詳細內容大概分為4個部分,1.應用場景 2.遇到問題 3.設計 4.實現 5.運行效果

1.應用場景

需要定時推送數據,且輕量化的實現。

2.遇到問題

  • 如果啟動一個定時器去定時輪詢
  • (1)輪詢效率比較低
  • (2)每次掃庫,已經被執(zhí)行過記錄,仍然會被掃描(只是不會出現在結果集中),會做重復工作
  • (3)時效性不夠好,如果每小時輪詢一次,最差的情況下會有時間誤差
  • 如何利用“延時消息”,對于每個任務只觸發(fā)一次,保證效率的同時保證實時性,是今天要討論的問題。

3.設計

高效延時消息,包含兩個重要的數據結構:

  1. 環(huán)形隊列,例如可以創(chuàng)建一個包含3600個slot的環(huán)形隊列(本質是個數組)
  2. 任務集合,環(huán)上每一個slot是一個Set

同時,啟動一個timer,這個timer每隔1s,在上述環(huán)形隊列中移動一格,有一個Current Index指針來標識正在檢測的slot。

Task結構中有兩個很重要的屬性:

  1. Cycle-Num:當Current Index第幾圈掃描到這個Slot時,執(zhí)行任務
  2. Task-Function:需要執(zhí)行的任務指針

假設當前Current Index指向第一格,當有延時消息到達之后,例如希望3610秒之后,觸發(fā)一個延時消息任務,只需:

  1. 計算這個Task應該放在哪一個slot,現在指向1,3610秒之后,應該是第11格,所以這個Task應該放在第11個slot的Set中
  2. 計算這個Task的Cycle-Num,由于環(huán)形隊列是3600格(每秒移動一格,正好1小時),這個任務是3610秒后執(zhí)行,所以應該繞3610/3600=1圈之后再執(zhí)行,于是Cycle-Num=1

Current Index不停的移動,每秒移動到一個新slot,這個slot中對應的Set,每個Task看Cycle-Num是不是0:

  1. 如果不是0,說明還需要多移動幾圈,將Cycle-Num減1
  2. 如果是0,說明馬上要執(zhí)行這個Task了,取出Task-Funciton執(zhí)行(可以用單獨的線程來執(zhí)行Task),并把這個Task從Set中刪除

使用了“延時消息”方案之后,“訂單48小時后關閉評價”的需求,只需將在訂單關閉時,觸發(fā)一個48小時之后的延時消息即可:

  1. 無需再輪詢全部訂單,效率高
  2. 一個訂單,任務只執(zhí)行一次
  3. 時效性好,精確到秒(控制timer移動頻率可以控制精度)

4.實現

首先寫一個方案要理清楚自己的項目結構,我做了如下分層。

Interfaces , 這層里主要約束延遲消息隊列的隊列和消息任務行。

public interface IRingQueue<T>
{
    /// <summary>
    /// Add tasks [add tasks will automatically generate: task Id, task slot location, number of task cycles]
    /// </summary>
    /// <param name="delayTime">The specified task is executed after N seconds.</param>
    /// <param name="action">Definitions of callback</param>
    void Add(long delayTime,Action<T> action);
    /// <summary>
    /// Add tasks [add tasks will automatically generate: task Id, task slot location, number of task cycles]
    /// </summary>
    /// <param name="delayTime">The specified task is executed after N seconds.</param>
    /// <param name="action">Definitions of callback.</param>
    /// <param name="data">Parameters used in the callback function.</param>
    void Add(long delayTime, Action<T> action, T data);
    /// <summary>
    /// Add tasks [add tasks will automatically generate: task Id, task slot location, number of task cycles]
    /// </summary>
    /// <param name="delayTime"></param>
    /// <param name="action">Definitions of callback</param>
    /// <param name="data">Parameters used in the callback function.</param>
    /// <param name="id">Task ID, used when deleting tasks.</param>
    void Add(long delayTime, Action<T> action, T data, long id);
    /// <summary>
    /// Remove tasks [need to know: where the task is, which specific task].
    /// </summary>
    /// <param name="index">Task slot location</param>
    /// <param name="id">Task ID, used when deleting tasks.</param>
    void Remove(long id);
    /// <summary>
    /// Launch queue.
    /// </summary>
    void Start();
}
 public interface ITask
 {
 }

Achieves,這層里實現之前定義的接口,這里寫成抽象類是為了后面方便擴展。

using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DelayMessageApp.Interfaces;
namespace DelayMessageApp.Achieves.Base
{
public abstract class BaseQueue<T> : IRingQueue<T>
{
    private long _pointer = 0L;
    private ConcurrentBag<BaseTask<T>>[] _arraySlot;
    private int ArrayMax;
    /// <summary>
    /// Ring queue.
    /// </summary>
    public ConcurrentBag<BaseTask<T>>[] ArraySlot
    {
        get { return _arraySlot ?? (_arraySlot = new ConcurrentBag<BaseTask<T>>[ArrayMax]); }
    }
    public BaseQueue(int arrayMax)
    {
        if (arrayMax < 60 && arrayMax % 60 == 0)
            throw new Exception("Ring queue length cannot be less than 60 and is a multiple of 60 .");
        ArrayMax = arrayMax;
    }
    public void Add(long delayTime, Action<T> action)
    {
        Add(delayTime, action, default(T));
    }
    public void Add(long delayTime,Action<T> action,T data)
    {
        Add(delayTime, action, data,0);
    }
    public void Add(long delayTime, Action<T> action, T data,long id)
    {
        NextSlot(delayTime, out long cycle, out long pointer);
        ArraySlot[pointer] =  ArraySlot[pointer] ?? (ArraySlot[pointer] = new ConcurrentBag<BaseTask<T>>());
        var baseTask = new BaseTask<T>(cycle, action, data,id);
        ArraySlot[pointer].Add(baseTask);
    }
    /// <summary>
    /// Remove tasks based on ID.
    /// </summary>
    /// <param name="id"></param>
    public void Remove(long id)
    {
        try
        {
            Parallel.ForEach(ArraySlot, (ConcurrentBag<BaseTask<T>> collection, ParallelLoopState state) =>
            {
                var resulTask = collection.FirstOrDefault(p => p.Id == id);
                if (resulTask != null)
                {
                    collection.TryTake(out resulTask);
                    state.Break();
                }
            });
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
    public void Start()
    {
        while (true)
        {
            RightMovePointer();
            Thread.Sleep(1000);
            Console.WriteLine(DateTime.Now.ToString());
        }
    }
    /// <summary>
    /// Calculate the information of the next slot.
    /// </summary>
    /// <param name="delayTime">Delayed execution time.</param>
    /// <param name="cycle">Number of turns.</param>
    /// <param name="index">Task location.</param>
    private void NextSlot(long delayTime, out long cycle,out long index)
    {
        try
        {
            var circle = delayTime / ArrayMax;
            var second = delayTime % ArrayMax;
            var current_pointer = GetPointer();
            var queue_index = 0L;
            if (delayTime - ArrayMax > ArrayMax)
            {
                circle = 1;
            }
            else if (second > ArrayMax)
            {
                circle += 1;
            }
            if (delayTime - circle * ArrayMax < ArrayMax)
            {
                second = delayTime - circle * ArrayMax;
            }
            if (current_pointer + delayTime >= ArrayMax)
            {
                cycle = (int)((current_pointer + delayTime) / ArrayMax);
                if (current_pointer + second - ArrayMax < 0)
                {
                    queue_index = current_pointer + second;
                }
                else if (current_pointer + second - ArrayMax > 0)
                {
                    queue_index = current_pointer + second - ArrayMax;
                }
            }
            else
            {
                cycle = 0;
                queue_index = current_pointer + second;
            }
            index = queue_index;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }
    /// <summary>
    /// Get the current location of the pointer.
    /// </summary>
    /// <returns></returns>
    private long GetPointer()
    {
        return Interlocked.Read(ref _pointer);
    }
    /// <summary>
    /// Reset pointer position.
    /// </summary>
    private void ReSetPointer()
    {
        Interlocked.Exchange(ref _pointer, 0);
    }
    /// <summary>
    /// Pointer moves clockwise.
    /// </summary>
    private void RightMovePointer()
    {
        try
        {
            if (GetPointer() >= ArrayMax - 1)
            {
                ReSetPointer();
            }
            else
            {
                Interlocked.Increment(ref _pointer);
            }
            var pointer = GetPointer();
            var taskCollection = ArraySlot[pointer];
            if (taskCollection == null || taskCollection.Count == 0) return;
            Parallel.ForEach(taskCollection, (BaseTask<T> task) =>
            {
                if (task.Cycle > 0)
                {
                    task.SubCycleNumber();
                }
                if (task.Cycle <= 0)
                {
                    taskCollection.TryTake(out task);
                    task.TaskAction(task.Data);
                }
            });
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }
}
}
using System;
using System.Threading;
using DelayMessageApp.Interfaces;
namespace DelayMessageApp.Achieves.Base
{
public class BaseTask<T> : ITask
{
    private long _cycle;
    private long _id;
    private T _data;
    public Action<T> TaskAction { get; set; }
    public long Cycle
    {
        get { return Interlocked.Read(ref _cycle); }
        set { Interlocked.Exchange(ref _cycle, value); }
    }
    public long Id
    {
        get { return _id; }
        set { _id = value; }
    }
    public T Data
    {
        get { return _data; }
        set { _data = value; }
    }
    public BaseTask(long cycle, Action<T> action, T data,long id)
    {
        Cycle = cycle;
        TaskAction = action;
        Data = data;
        Id = id;
    }
    public BaseTask(long cycle, Action<T> action,T data)
    {
        Cycle = cycle;
        TaskAction = action;
        Data = data;
    }
    public BaseTask(long cycle, Action<T> action)
    {
        Cycle = cycle;
        TaskAction = action;
    }
    public void SubCycleNumber()
    {
        Interlocked.Decrement(ref _cycle);
    }
}
}

Logic,這層主要實現調用邏輯,調用者最終只需要關心把任務放進隊列并指定什么時候執(zhí)行就行了,根本不需要關心其它的任何信息。

public static void Start()
{
    //1.Initialize queues of different granularity.
    IRingQueue<NewsModel> minuteRingQueue = new MinuteQueue<NewsModel>();
    //2.Open thread.
    var lstTasks = new List<Task>
    {
        Task.Factory.StartNew(minuteRingQueue.Start)
    };
    //3.Add tasks performed in different periods.
    minuteRingQueue.Add(5, new Action<NewsModel>((NewsModel newsObj) =>
    {
        Console.WriteLine(newsObj.News);
    }), new NewsModel() { News = "Trump's visit to China!" });
    minuteRingQueue.Add(10, new Action<NewsModel>((NewsModel newsObj) =>
    {
        Console.WriteLine(newsObj.News);
    }), new NewsModel() { News = "Putin Pu's visit to China!" });
    minuteRingQueue.Add(60, new Action<NewsModel>((NewsModel newsObj) =>
    {
        Console.WriteLine(newsObj.News);
    }), new NewsModel() { News = "Eisenhower's visit to China!" });
    minuteRingQueue.Add(120, new Action<NewsModel>((NewsModel newsObj) =>
    {
        Console.WriteLine(newsObj.News);
    }), new NewsModel() { News = "Xi Jinping's visit to the US!" });
    //3.Waiting for all tasks to complete is usually not completed. Because there is an infinite loop.
    //F5 Run the program and see the effect.
    Task.WaitAll(lstTasks.ToArray());
    Console.Read();
}

Models,這層就是用來在延遲任務中帶入的數據模型類而已了。自己用的時候換成任意自定義類型都可以。

5.運行效果

到此這篇關于如何實現定時推送的具體方案的文章就介紹到這了,希望對大家有所幫助,更多相關C#內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持腳本之家!

相關文章

  • C#動態(tài)生成按鈕及定義按鈕事件的方法

    C#動態(tài)生成按鈕及定義按鈕事件的方法

    這篇文章主要介紹了C#動態(tài)生成按鈕及定義按鈕事件的方法,涉及C#按鈕操作的相關技巧,需要的朋友可以參考下
    2015-05-05
  • C#使用System.Threading.Timer實現計時器的示例詳解

    C#使用System.Threading.Timer實現計時器的示例詳解

    以往一般都是用 System.Timers.Timer 來做計時器,其實 System.Threading.Timer 也可以實現計時器功能,下面就跟隨小編一起來學習一下如何使用System.Threading.Timer實現計時器功能吧
    2024-01-01
  • C#中實現線程安全單例模式的多種方法

    C#中實現線程安全單例模式的多種方法

    在C#中實現線程安全的單例模式通常涉及確保類的實例在多線程環(huán)境中只被創(chuàng)建一次,并且這個實例在應用程序的生命周期內是唯一的,以下是幾種常見的方法來實現線程安全的單例模式,需要的朋友可以參考下
    2025-01-01
  • C# Request.Form用法案例詳解

    C# Request.Form用法案例詳解

    這篇文章主要介紹了C# Request.Form用法案例詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下
    2021-08-08
  • C#語法相比其它語言比較獨特的地方(一)

    C#語法相比其它語言比較獨特的地方(一)

    這篇文章主要介紹了C#語法相比其它語言比較獨特的地方(一),本文講解了switch語句可以用來測試string型的對象、多維數組、foreach語句、索引器和Property等內容,需要的朋友可以參考下
    2015-04-04
  • C# SaveFileDialog與OpenFileDialog用法案例詳解

    C# SaveFileDialog與OpenFileDialog用法案例詳解

    這篇文章主要介紹了C# SaveFileDialog與OpenFileDialog用法案例詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下
    2021-08-08
  • C#?WPF中RadioButton控件的用法及應用場景

    C#?WPF中RadioButton控件的用法及應用場景

    在WPF應用程序中,RadioButton控件是一種常用的用戶界面元素,本文主要介紹了C#?WPF中RadioButton控件的用法及應用場景,具有一定的參考價值,感興趣的可以了解一下
    2024-03-03
  • Unity3D運行報DllNotFoundException錯誤的解決方案

    Unity3D運行報DllNotFoundException錯誤的解決方案

    這篇文章主要介紹了Unity3D運行報DllNotFoundException錯誤的解決方案,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-04-04
  • .net(c#)中的new關鍵字詳細介紹

    .net(c#)中的new關鍵字詳細介紹

    在 C# 中,new 關鍵字可用作運算符、修飾符或約束
    2013-10-10
  • Unity實現桌面反彈的示例代碼

    Unity實現桌面反彈的示例代碼

    反彈球是小時候都玩過的網頁小游戲,但是很多人都不知道怎樣實現,本文就來介紹一下Unity實現桌面反彈的示例代碼,感興趣的可以了解一下
    2021-05-05

最新評論

长海县| 宝应县| 濉溪县| 始兴县| 广德县| 普定县| 阳东县| 武城县| 宜兰县| 高邑县| 桂平市| 龙南县| 建宁县| 钟山县| 孟津县| 丰原市| 古丈县| 玛曲县| 宝清县| 汝南县| 桦南县| 济南市| 清远市| 招远市| 五指山市| 石城县| 屏东县| 忻州市| 昌宁县| 岢岚县| 二手房| 绍兴县| 垣曲县| 新宁县| 木里| 江门市| 宁明县| 深州市| 礼泉县| 舟山市| 大竹县|