/// <summary>把定时器加入队列</summary> /// <param name="timer"></param> public static void Add(TimerX timer) { WriteLog("TimerX.Add {0}ms {1}", timer.Period, timer); lock (timers) { timers.Add(timer); if (thread == null) { thread = new Thread(Process); //thread.Name = "TimerX"; thread.Name = "T"; thread.IsBackground = true; thread.Start(); } var e = waitForTimer; if (e != null) { var swh = e.SafeWaitHandle; if (swh != null && !swh.IsClosed) { e.Set(); } } } }
/// <summary>开始</summary> public void Start() { if (Client == null) { Client = new UdpServer(); Client.Received += Client_Received; Client.Open(); _Timer = new TimerX(s => { try { SendDiscover(); } catch (Exception ex) { WriteLog(ex.ToString()); } }, null, 0, 1000); } //var rnd = new Random(); TransID = Rand.Next(); if (_Mac == null || _Mac.Length == 0) _Mac = HardInfo.Current.Macs.Replace(":", null).ToHex(); if (_Mac == null || _Mac.Length == 0) _Mac = Rand.NextBytes(6); }
/// <summary> /// 构造器 /// </summary> private MonitorStatManager() { //--启动监控中心对外提供服务 m_MonitorCenter = new MonitorCenter(); m_MonitorCenter.Start(); //--初始化监控统计数据结构 m_MonitorStatData = new MonitorStatData(); //--每隔60秒钟将监控数据保存到数据库中并清空 m_TimerMonitorStatDataSave = new TimerX(x => { SaveToDatabase(m_MonitorStatData); lock (m_TimerMonitorStatDataSave) { m_MonitorStatData = new MonitorStatData(); } }, null, 1000 * 60, 1000 * 60); //--每隔1秒钟对外发布一次监控统计数据 m_TimerMonitorStatDataPublish = new TimerX(x => { PublishMointorData(m_MonitorStatData); }, null, 1000, 1000); }
/// <summary>把定时器加入队列</summary> /// <param name="timer"></param> public void Add(TimerX timer) { WriteLog("Timer.Add {0}ms {1}", timer.Period, timer); lock (this) { var list = new List <TimerX>(Timers); if (list.Contains(timer)) { return; } list.Add(timer); Timers = list.ToArray(); Count++; if (thread == null) { thread = new Thread(Process) { //thread.Name = "TimerX"; Name = Name == "Default" ? "T" : Name, IsBackground = true }; thread.Start(); } Wake(); } //if (timers.Count > 100 && XTrace.Debug) XTrace.WriteLine("{0} 任务过多 {1}>{2},请考虑使用新的调度器", Name, timers.Count, 100); }
/// <summary>检查定时器是否到期</summary> /// <param name="timer"></param> /// <param name="now"></param> /// <returns></returns> private Boolean CheckTime(TimerX timer, DateTime now) { // 删除过期的,为了避免占用过多CPU资源,TimerX禁止小于10ms的任务调度 var p = timer.Period; if (p < 10 && p > 0) { // 周期0表示只执行一次 if (p < 10 && p > 0) { XTrace.WriteLine("为了避免占用过多CPU资源,TimerX禁止小于{1}ms<10ms的任务调度,关闭任务{0}", timer, p); } timer.Dispose(); return(false); } var ts = timer.NextTime - now; //var d = (Int64)ts.TotalMilliseconds; //var d = Math.Ceiling(ts.TotalMilliseconds); var d = ts.TotalMilliseconds; if (d > 0) { // 缩小间隔,便于快速调用 if (d < period) { period = (Int32)d; } return(false); } //XTrace.WriteLine("d={0}", ts.TotalMilliseconds); return(true); }
/// <summary>把定时器加入队列</summary> /// <param name="timer"></param> public void Add(TimerX timer) { WriteLog("Timer.Add {0}ms {1}", timer.Period, timer); lock (timers) { timers.Add(timer); Count++; if (thread == null) { thread = new Thread(Process) { //thread.Name = "TimerX"; Name = Name == "Default" ? "T" : Name, IsBackground = true }; thread.Start(); } Wake(); } //if (timers.Count > 100 && XTrace.Debug) XTrace.WriteLine("{0} 任务过多 {1}>{2},请考虑使用新的调度器", Name, timers.Count, 100); }
/// <summary> /// 重新连接到注册中心,采用定时器5秒后重连 /// </summary> private void ReConnect() { if (m_CometClient != null) m_CometClient.Dispose(); m_TimerX = new TimerX(x => Connect(), null, 5000, 5000); }
/// <summary> /// 连接到注册中心 /// </summary> /// <returns></returns> internal void Connect() { String uri = m_ESBProxy.ConsumerConfig.Registry[0].Uri; if (m_ESBProxy.ConsumerConfig.ApplicationName.StartsWith("ESB_CallCenter")) m_CometClient = new CometClient(uri, CometClientType.CallCenter); else if (m_ESBProxy.ConsumerConfig.ApplicationName.StartsWith("ESB_Portal")) m_CometClient = new CometClient(uri, CometClientType.Portal); else if (m_ESBProxy.ConsumerConfig.ApplicationName.StartsWith("ESB_Monitor")) m_CometClient = new CometClient(uri, CometClientType.Monitor); else if (m_ESBProxy.ConsumerConfig.ApplicationName.StartsWith("ESB_QueueCenter")) m_CometClient = new CometClient(uri, CometClientType.QueueCenter); else m_CometClient = new CometClient(uri, CometClientType.Consumer); m_CometClient.OnReceiveNotify += m_CometClient_OnReceiveNotify; m_CometClient.Connect(); //--连接成功后,释放定时器 if (m_TimerX != null) { m_TimerX.Dispose(); m_TimerX = null; } }
private void Notify() { // 扫描一次,一旦发送有消息,则调用线程池线程处理 if (_Timer == null) _Timer = new TimerX(Push, null, 0, 5000); else _Timer.NextTime = DateTime.MinValue; }
static void ProcessItem(TimerX timer) { // 删除过期的 if (!timer.Callback.IsAlive) { lock (timers) { timers.Remove(timer); timer.Dispose(); } return; } TimeSpan ts = timer.NextTime - DateTime.Now; Int32 d = (Int32)ts.TotalMilliseconds; if (d > 0) { // 缩小间隔,便于快速调用 if (d < period) { period = d; } return; } //WriteLog("TimerX.Process {0}", timer); try { timer.Calling = true; Action <Object> callback = timer.Callback; // 线程池调用 if (timer.UseThreadPool) { ThreadPoolX.QueueUserWorkItem(delegate() { callback(timer.State); }); } else { callback(timer.State); } } catch (ThreadAbortException) { throw; } catch (ThreadInterruptedException) { throw; } catch { } finally { timer.Timers++; timer.Calling = false; timer.NextTime = DateTime.Now.AddMilliseconds(timer.Period); if (timer.Period < period) { period = timer.Period; } } }
void frm_FormClosing(object sender, FormClosingEventArgs e) { SaveInfo(); _timer.Dispose(); _timer = null; if (Port != null) Port.Close(); }
/// <summary>延迟执行一个委托</summary> /// <param name="callback"></param> /// <param name="ms"></param> /// <returns></returns> public static TimerX Delay(WaitCallback callback, Int32 ms) { var timer = new TimerX(callback, null, ms, 0) { Async = true }; return(timer); }
/// <summary>处理每一个定时器</summary> /// <param name="timer"></param> private void ProcessItem(TimerX timer) { TimerX.Current = timer; var sw = new Stopwatch(); sw.Start(); try { timer.Calling = true; timer.Callback(timer.State ?? timer); } catch (ThreadAbortException) { throw; } catch (ThreadInterruptedException) { throw; } // 如果用户代码没有拦截错误,则这里拦截,避免出错了都不知道怎么回事 catch (Exception ex) { XTrace.WriteException(ex); } finally { sw.Stop(); var d = (Int32)sw.ElapsedMilliseconds; if (timer.Cost == 0) { timer.Cost = d; } else { timer.Cost = (timer.Cost + d) / 2; } if (d > 500 && !timer.Async) { XTrace.WriteLine("任务 {0} 耗时过长 {1:n0}ms", timer, d); } // 再次读取周期,因为任何函数可能会修改 var p = timer.Period; timer.Timers++; timer.NextTime = DateTime.Now.AddMilliseconds(p); timer.Calling = false; // 清理一次性定时器 if (p <= 0) { timer.Dispose(); } else if (p < period) { period = p; } TimerX.Current = null; } }
/// <summary> /// 连接到监控中心 /// </summary> /// <returns></returns> public void Connect() { m_CometClient = new CometClient(m_MonitorCenterUri, m_CometClientType); m_CometClient.OnReceiveNotify += m_CometClient_OnReceiveNotify; m_CometClient.Connect(); //--连接成功后,释放定时器 if (m_TimerX != null) { m_TimerX.Dispose(); m_TimerX = null; } }
private void SerialPortList_Load(object sender, EventArgs e) { LoadInfo(); // 挂载定时器 _timer = new TimerX(OnCheck, null, 300, 300); var frm = Parent as Form; if (frm != null) { frm.FormClosing += frm_FormClosing; } }
public static void Remove(TimerX timer) { if (timer == null) { return; } WriteLog("TimerX.Remove {0}", timer); lock (timers) { if (timers.Contains(timer)) { timers.Remove(timer); } } }
public static void Add(TimerX timer) { lock (timers) { timers.Add(timer); WriteLog("TimerX.Add {0}ms {1}", timer.Period, timer); timer.OnDisposed += new EventHandler(delegate(Object sender, EventArgs e) { var tx = sender as TimerX; if (tx == null) { return; } lock (timers) { WriteLog("TimerX.Remove {0}", tx); if (timers.Contains(tx)) { timers.Remove(tx); } } }); if (thread == null) { thread = new Thread(Process); //thread.Name = "TimerX"; thread.Name = "T"; thread.IsBackground = true; thread.Start(); } if (waitForTimer != null && waitForTimer.SafeWaitHandle != null && !waitForTimer.SafeWaitHandle.IsClosed) { waitForTimer.Set(); } } }
/// <summary>把定时器加入队列</summary> /// <param name="timer"></param> public void Add(TimerX timer) { WriteLog("Timer.Add {0}ms {1}", timer.Period, timer); lock (timers) { timers.Add(timer); Count++; if (thread == null) { thread = new Thread(Process); //thread.Name = "TimerX"; thread.Name = Name == "Default" ? "T" : Name; thread.IsBackground = true; thread.Start(); } Wake(); } }
/// <summary>从队列删除定时器</summary> /// <param name="timer"></param> public void Remove(TimerX timer) { if (timer == null) { return; } WriteLog("Timer.Remove {0}", timer); lock (this) { var list = new List <TimerX>(Timers); if (list.Contains(timer)) { list.Remove(timer); Timers = list.ToArray(); Count--; } } }
private void btnStart_Click(object sender, EventArgs e) { btnStart.Enabled = false; btnStop.Enabled = true; //CallService(); m_TestManager.Start(new ESBInvokeParam() { CallCenterUrl = this.txtCallCenterUrl.Text, ServiceName = this.txtServiceName.Text, MethodName = this.txtMethodName.Text, Message = this.txtMessage.Text, Version = 1 }); m_TimerX = new TimerX(x => { this.lblInvokeNum.Invoke(new UpdateLabel(UpdateInvokeNumLabel), m_TestManager.InvokeNum); }, null, 1000, 1000); }
/// <summary>处理每一个定时器</summary> /// <param name="timer"></param> static void ProcessItem(TimerX timer) { try { timer.Calling = true; Action <Object> callback = timer.Callback; callback(timer.State ?? timer); } catch (ThreadAbortException) { throw; } catch (ThreadInterruptedException) { throw; } // 如果用户代码没有拦截错误,则这里拦截,避免出错了都不知道怎么回事 catch (Exception ex) { XTrace.WriteException(ex); } finally { // 再次读取周期,因为任何函数可能会修改 var p = timer.Period; timer.Timers++; timer.NextTime = DateTime.Now.AddMilliseconds(p); timer.Calling = false; // 清理一次性定时器 if (p <= 0) { lock (timers) { timers.Remove(timer); timer.Dispose(); } } if (p < period) { period = p; } } }
/// <summary>检查定时器是否到期</summary> /// <param name="timer"></param> /// <param name="now"></param> /// <returns></returns> static Boolean CheckTime(TimerX timer, DateTime now) { // 删除过期的,为了避免占用过多CPU资源,TimerX禁止小于10ms的任务调度 var p = timer.Period; if (!timer.Callback.IsAlive || p < 10 && p > 0) { // 周期0表示只执行一次 if (p < 10 && p > 0) { XTrace.WriteLine("为了避免占用过多CPU资源,TimerX禁止小于{1}ms<10ms的任务调度,关闭任务{0}", timer, p); } lock (timers) { timers.Remove(timer); timer.Dispose(); } return(false); } var ts = timer.NextTime - now; var d = (Int32)ts.TotalMilliseconds; if (d > 0) { // 缩小间隔,便于快速调用 if (d < period) { period = d; } return(false); } return(true); }
/// <summary>串口传输</summary> public SerialTransport() { // 每隔一段时间检查一次串口是否已经关闭,如果串口已经不存在,则关闭该传输口 timer = new TimerX(CheckDisconnect, null, 3000, 3000); }
private void Connect() { if (!m_IsConnected && m_ESBProxy.ESBConfig != null && m_ESBProxy.ESBConfig.Cache != null && m_ESBProxy.ESBConfig.Cache.Count > 0) { try { String[] paramUri= m_ESBProxy.ESBConfig.Cache[0].Uri.Split(':'); m_RedisClient = new RedisClient(paramUri[0], Int32.Parse(paramUri[1])); m_RedisClient.Set<String>(String.Format("MBSOA_Consumer:{0}:{1}", m_ESBProxy.ConsumerConfig.ApplicationName, m_ESBProxy.ClientIP) , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); m_IsConnected = true; XTrace.WriteLine("成功连接到缓存中心。"); if (m_TimerX != null) //--说明监控中心曾经不可用过 { m_TimerX.Dispose(); m_TimerX = null; m_ReConnectNum = 0; } } catch (Exception ex) { m_IsConnected = false; if (m_TimerX == null) { lock (m_TimerXLock) { m_TimerX = new TimerX(x => Connect(), null, 20000, 20000); XTrace.WriteLine("无法连接到缓存中心:" + ex.Message); } } else { XTrace.WriteLine("第{0}次重连缓存中心失败, 抛出异常:{1}", m_ReConnectNum, ex.Message); m_ReConnectNum++; } } } }
/// <summary>异步多次发送数据</summary> /// <param name="session">会话</param> /// <param name="buffer"></param> /// <param name="times"></param> /// <param name="msInterval"></param> /// <returns></returns> public static Boolean SendAsync(this ISocketRemote session, Byte[] buffer, Int32 times, Int32 msInterval) { if (times <= 1) return session.SendAsync(buffer); if (msInterval < 10) { for (int i = 0; i < times; i++) { session.SendAsync(buffer); } return true; } //var src = new TaskCompletionSource<Int32>(); var timer = new TimerX(s => { session.SendAsync(buffer); //session.Send(buffer); // 如果次数足够,则把定时器周期置空,内部会删除 var t = s as TimerX; if (--times <= 0) { t.Period = 0; //src.SetResult(0); } }, null, 0, msInterval); //return src.Task; return true; }
public static void Add(TimerX timer) { lock (timers) { timers.Add(timer); timer.OnDisposed += new EventHandler(delegate(Object sender, EventArgs e) { TimerX tx = sender as TimerX; if (tx == null) return; lock (timers) { if (timers.Contains(tx)) timers.Remove(tx); } }); if (thread == null) { thread = new Thread(Process); thread.Name = "TimerX"; thread.IsBackground = true; thread.Start(); } if (waitForTimer != null && waitForTimer.SafeWaitHandle != null && !waitForTimer.SafeWaitHandle.IsClosed) waitForTimer.Set(); } }
static void ProcessItem(TimerX timer) { // 删除过期的 if (!timer.Callback.IsAlive) { lock (timers) { timers.Remove(timer); } return; } TimeSpan ts = timer.NextTime - DateTime.Now; Int32 d = (Int32)ts.TotalMilliseconds; if (d > 0) { // 缩小间隔,便于快速调用 if (d < period) period = d; return; } try { timer.Calling = true; Action<Object> callback = timer.Callback; // 线程池调用 if (timer.UseThreadPool) ThreadPoolX.QueueUserWorkItem(delegate() { callback(timer.State); }); else callback(timer.State); } catch (ThreadAbortException) { throw; } catch (ThreadInterruptedException) { throw; } catch { } finally { timer.Timers++; timer.Calling = false; timer.NextTime = DateTime.Now.AddMilliseconds(timer.Period); if (timer.Period < period) period = timer.Period; } }