PeriodicallySaveData.cs 2.65 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FLY.OBJComponents.Server
{
    /// <summary>
    /// 周期保存数据,写入到数据库的周期为20s; 
    /// 但数据的周期最小为1s
    /// </summary>
    public class PeriodicallySaveData<T>
    {
        Stopwatch stopwatch_interval = new Stopwatch();
        Stopwatch stopwatch_1min = new Stopwatch();
        List<T> dbWidths_1min = new List<T>();
        /// <summary>
        /// 数据保存周期,单位s
        /// </summary>
        public int IntervalSec = 5;
        /// <summary>
        /// 把缓存区的数据一次性导出
        /// </summary>
        public Action<List<T>> SaveList;
        /// <summary>
        /// 创造一次数据
        /// </summary>
        public Func<T> CreateData;

        public void Init(int intervalSec, Action<List<T>> saveList, Func<T> createData)
        {
            IntervalSec = intervalSec;
            SaveList = saveList;
            CreateData = createData;
            FObjBase.PollModule.Current.Poll_Config(
                FObjBase.PollModule.POLL_CONFIG.ADD, OnPoll, TimeSpan.FromSeconds(1));
        }
        void OnPoll()
        {
            if (stopwatch_1min.IsRunning && stopwatch_1min.Elapsed >= TimeSpan.FromSeconds(20))
            {
                //启动了1min 且到点了
                if (dbWidths_1min.Count > 0)
                {
                    SaveList(dbWidths_1min);
                    dbWidths_1min.Clear();
                    stopwatch_1min.Restart();
                }
                else
                {
                    stopwatch_1min.Reset();
                }
            }

            if (!stopwatch_interval.IsRunning)
            {
                stopwatch_interval.Start();
                return;
            }
            else
            {
                if (stopwatch_interval.Elapsed < TimeSpan.FromSeconds(IntervalSec))
                    return;
                else
                    stopwatch_interval.Restart();
            }

            //记录数据
            T db_Width = CreateData();
            if (db_Width == null)
            {
                //没有,退出
                return;
            }

            //写入数据库
            if (!stopwatch_1min.IsRunning)
            {
                //第1次立刻写入
                SaveList(new List<T> { db_Width });
                stopwatch_1min.Start();
            }
            else
            {
                //第2次,1分钟后才能保存
                dbWidths_1min.Add(db_Width);
            }
        }
    }
}