using Newtonsoft.Json.Linq;
using Rhea.Common;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Tiger.Business.MES.Transaction;
using Tiger.IBusiness;
using Tiger.Model;
namespace Tiger.Business.DbCache
{
///
/// 岗位数据库数据缓存
///
public class MesPositionCache : IMesPositionCache
{
#region Variables
private WhileThread AutoUpdateThread;
private DateTime LastUpdateTime = DateTime.MinValue;
#endregion
#region Propertys
public string Id { get; set; } = Guid.NewGuid().ToString("N");
public string Tag { get; set; } = "MesPositionCache";
public string Name { get; set; } = "MesPositionCache";
public bool IsRunning { get; set; }
private List _Positions = new();
public List Positions { get { Update(); return _Positions; } set => _Positions = value; }
public MES_POSITION this[string code] { get { Update(); return _Positions.FirstOrDefault(q => q.POST_CODE == code); } }
#endregion
#region Functions
///
/// 启动自动更新缓存
///
public void Start()
{
try
{
AutoUpdateThread = new(AutoUpdate);
AutoUpdateThread.Start();
Logger.Default.Info("Start MesPosition Cache Auto Update Thread");
}
catch (System.Exception ex)
{
Logger.Default.Fatal(ex, "Start MesPosition Cache Auto Update Thread Exception");
}
}
///
/// 关闭自动更新缓存
///
public void Stop()
{
try
{
AutoUpdateThread?.Stop();
Logger.Console.Info("Stop MesPosition Cache Auto Update Thread");
}
catch (System.Exception ex)
{
Logger.Console.Fatal(ex, "Stop MesPosition Cache Auto Update Thread Exception");
}
}
///
/// 更新数据缓存
///
public void Update()
{
var lastUpdate = Biz.Db.Queryable().Max(q => q.UPDATE_TIME);
if (LastUpdateTime < lastUpdate)
{
_Positions = Biz.Db.Queryable().IncludesAllFirstLayer().ToList();
LastUpdateTime = lastUpdate;
Logger.Console.Info($"Get MesPosition successful, total {Positions.Count}, last update time is {LastUpdateTime:yyyy-MM-dd HH:mm:ss}");
}
}
///
/// 自动更新
///
private void AutoUpdate()
{
try
{
Update();
}
catch (System.Exception ex)
{
Logger.Console.Fatal(ex, "MesPosition Cache Auto Update Exception");
LastUpdateTime = DateTime.MinValue;
}
//休眠30分钟
Thread.Sleep(30 * 60 * 1000);//
}
#endregion
}
}