using SlnMesnac.LabelPrint.BarTender; using SlnMesnac.LabelPrint.Common; using SlnMesnac.LabelPrint.Log4net; using SlnMesnac.LabelPrint.TaskQueue; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SlnMesnac.LabelPrint.Timer { public class PrintTimer { private readonly LogHelper logHelper = LogHelper.Instance; private readonly TaskHelper taskHelper = TaskHelper.Instance; private readonly PrintManager printManager = PrintManager.Instance; private readonly JsonChange jsonChange = JsonChange.Instance; private System.Timers.Timer timer = new System.Timers.Timer(5000); /// /// 日志刷新 /// /// public delegate void LogRefresh(string massage); public event LogRefresh LogRefreshEvent; #region 单例实现 private static readonly Lazy lazy = new Lazy(() => new PrintTimer()); public static PrintTimer Instance { get { return lazy.Value; } } #endregion private PrintTimer() { } /// /// 开启自动打印 /// /// public bool StartPrint() { bool result = false; try { if (!timer.Enabled) { timer.Elapsed += new System.Timers.ElapsedEventHandler(ReadRfidByTimer); timer.AutoReset = true; timer.Enabled = false; timer.Start(); this.PrintMessageToListBox("开启定时任务自动执行标签打印"); } result = true; }catch(Exception ex) { logHelper.Error("自动打印定时任务启动异常", ex); this.PrintMessageToListBox($"自动打印定时任务启动异常:{ex.Message}"); } return result; } private void ReadRfidByTimer(object source, System.Timers.ElapsedEventArgs e) { try { var info = taskHelper.GetTask(); if (info == null) { this.PrintMessageToListBox("未获取到需要打印的任务"); } else { this.PrintMessageToListBox($"开始打印标签信息:{jsonChange.ModeToJson(info)}"); Thread.Sleep(200); if (info.column_A == null) { this.PrintMessageToListBox($"{info.productType}打印任务执行失败,A列数据为空"); return; } var printResult = printManager.Print(info); if (printResult) { this.PrintMessageToListBox($"{info.productType}打印{info.column_A.ToString()};打印成功"); } else { this.PrintMessageToListBox($"{info.column_A.ToString()};打印失败"); } taskHelper.RemoveTask(info); } }catch(Exception ex) { logHelper.Error("自动打印任务执行异常", ex); this.PrintMessageToListBox($"自动打印任务执行异常:{ex.Message}"); } } /// /// 停止自动打印 /// /// public bool StopPrint() { bool result = false; try { this.PrintMessageToListBox("停止自动打印,并释放定时任务"); if (timer.Enabled) { timer.Stop(); timer.Close(); timer.Dispose(); timer = new System.Timers.Timer(5000); } result = true; } catch (Exception ex) { logHelper.Error("自动打印定时任务停止异常", ex); this.PrintMessageToListBox($"自动打印定时任务停止异常:{ex.Message}"); } return result; } /// /// 日志打印 /// /// private void PrintMessageToListBox(string message) { LogRefreshEvent?.Invoke(message); } } }