public override void IntializeMonitor() { _timerHelper = new ThreadTimer($"{CategoryName}:{MonitorName ?? string.Empty}:{HeartBeatData.CounterName}"); _timerHelper.TimerEvent += (timer, state) => OnHeartbeat(this); StartTimer(HeartBeatIntervalInSeconds); }
private void Disconnecting() { ThreadTimer.Start((s) => { try { if (!checkIsConnected()) { this.OnDisconnected?.Invoke(s, "Socket Diconnected"); this.IsConnected = false; return(false); } else { if (!this.IsConnected) { this.OnError?.Invoke(this.client, "Socket Reconnecting..."); } this.IsConnected = true; return(true); } } catch (Exception ex) { this.OnError?.Invoke(this.client, string.Format("Socket Diconnecting error {0}", ex.Message)); return(false); } }, 500, this.client); }
/// <summary> /// Starts the connector and connects to the server /// </summary> public override void Run() { _running = true; ConnectSafe(); if (_timer != null) { return; } _timer = new ThreadTimer(() => { if (!IsRunning) { _timer.Stop(); _timer = null; return; } if (NeedReconnect() && !_connecting) { ConnectSafe(); } }, Interval); _timer.Start(ThreadPriority.BelowNormal); }
public void CreateDisposeAfterStarting() { var timer = new ThreadTimer(); timer.Start(); timer.Dispose(); }
public void Run_WorkCount_ExtraInterfaceBusy() { int realWorkCount = 0; EventHandler workChangedHandler = (sender, e) => { realWorkCount++; Thread.Sleep(200); }; int realInterfaceCount = 0; EventHandler interfaceChangedHandler = (sender, e) => { realInterfaceCount++; Thread.Sleep(1500); }; ThreadTimer threadTimer = new ThreadTimer(); threadTimer.Period = 10; threadTimer.Delay = 1; threadTimer.WorkChanged += workChangedHandler; threadTimer.InterfaceChanged += interfaceChangedHandler; threadTimer.Run(); Thread.Sleep(10000); Console.WriteLine(string.Format("realWorkCount = {0}; threadTimer.WorkCount = {1}, cycleCount = {2}, realInterfaceCount = {3}", realWorkCount, threadTimer.WorkCount, threadTimer.CycleCount, realInterfaceCount)); Assert.IsTrue(realWorkCount > 40 && threadTimer.WorkCount > 40 && threadTimer.CycleCount > 40 && realInterfaceCount < 8); }
private void Receiving() { ThreadTimer.Start((s) => { try { if (this.checkIsConnected()) { // Receive the response from the remote device. this.Receive(s); this.receiveDone.WaitOne(); return(true); } else { return(false); } } catch (Exception ex) { this.OnError?.Invoke(this.client, string.Format("Socket Receiving error {0}", ex.Message)); return(false); } }, 500, this.client); }
/// <summary> /// Инициализация переменных. /// </summary> public void Init() { Version = "v1.0.1"; InitTime = DateTime.Now; string fileName = Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location); varXml = new VarXml(string.Format("{0}.xml", fileName)); varXml.LoadFromXML(); CollectionWithUnits = new XPCollectionWithUnits(); DeviceCollection = (CollectionWithUnits.Add(typeof(Device))).Collection; DeviceRealCollection = new Collection <DeviceReal>(); CopyDataToReal(); // Отправка значений на интерфейс. foreach (DeviceReal deviceReal in DeviceRealCollection) { deviceReal.SendDataToXPObject(); } ThreadMain = new ThreadTimer(); ThreadMain.Period = varXml.ThreadMainPeriod; ThreadMain.WorkChanged += new EventHandler(ThreadMain_WorkChanged); ThreadMain.Run(); ThreadMainDelay = varXml.ThreadMainDelay; AppName = varXml.AppName; WorkerReboot = new BackgroundWorker(); WorkerReboot.DoWork += new DoWorkEventHandler(WorkerReboot_DoWork); }
/// <summary> /// Runs the queue time keeper timer /// </summary> public void Run() { TimeSpan interval = TimeSpan.FromMilliseconds(1000); _timer = new ThreadTimer(async() => await Elapse(), interval); _timer.Start(); }
public void StopTwice() { using (var timer = new ThreadTimer()) { timer.Stop(); timer.Stop(); } }
/// <summary> /// Stop shrink timer /// </summary> internal void Stop() { if (_autoShrinkTimer != null) { _autoShrinkTimer.Stop(); _autoShrinkTimer = null; } }
private void DisposeTimer() { this.SettingTimer.Stop(); this.SettingTimer.Enabled = false; this.SettingTimer.Elapsed -= new System.Timers.ElapsedEventHandler(this.SettingTimer_Elapsed); this.SettingTimer = null; this.LogAction("Dispose Timer"); }
private void DisposeTimer() { this.SettingTimer.Stop(); this.SettingTimer.Enabled = false; this.SettingTimer.Elapsed -= new System.Timers.ElapsedEventHandler(this.SettingTimer_Elapsed); this.SettingTimer = null; this.LogAction(CacheAction.General, CacheActionState.None, "Dispose Timer"); }
public override void IntializeMonitor() { _queue = new LoopQueue(_averagePeriod, AverageIntervalInMinutes); _threadTimer = new ThreadTimer(); _threadTimer.TimerEvent += (timer, state) => OnAverageTic(this); StartTimer(AverageIntervalInMinutes); }
private void InitializeTimer() { this.SettingTimer = new ThreadTimer((long)(this.IntervalSeconds)); this.SettingTimer.AutoReset = true; this.SettingTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.SettingTimer_Elapsed); this.SettingTimer.Enabled = true; this.SettingTimer.Start(); this.LogAction("Initialized Timer Interval:{0}", new string[] { this.SettingTimer.Interval.ToString() }); }
public override void IntializeMonitor() { _successQueue = new LoopQueue(_averagePeriod, AverageIntervalInMinutes); _failureQueue = new LoopQueue(_averagePeriod, AverageIntervalInMinutes); _attemptsQueue = new LoopQueue(_averagePeriod, AverageIntervalInMinutes); _timerHelper = new ThreadTimer($"{CategoryName}:{MonitorName ?? string.Empty}: OnAverage"); _timerHelper.TimerEvent += (timer, state) => OnAverageTic(this); StartTimer(AverageIntervalInMinutes); }
private void StartTimer() { _startTimer = new ThreadTimer(() => { if (_connection.HasTimedOut) { return; } DequeueAndRun(); }, AtemConstants.DataTransferCheckInterval); }
/// <summary> /// Destroys the queue time keeper. /// </summary> public async Task Destroy() { Reset(); if (_timer != null) { _timer.Stop(); _timer = null; } await Task.CompletedTask; }
/// <summary> /// Старт мониторинга онлайна. /// </summary> public void RunOnline() { PositionThread = new ThreadTimer() { Period = 1000, Delay = 500 }; PositionThread.WorkChanged += PositionThread_WorkChanged; PositionThread.InterfaceChanged += PositionThread_InterfaceChanged; PositionThread.Run(); OnlineChangedDelegate = OnlineChangedMethod; OnlineCountChangedDelegate = OnlineCountChangedMethod; }
/// <summary> /// Creates new absolute connector /// </summary> public AbsoluteConnector(TimeSpan reconnectInterval, Func <TClient> createInstance = null) : base(reconnectInterval, createInstance) { MessageExpiration = TimeSpan.Zero; MaximumTryCount = 0; _failedMessages = new List <FailedMessage>(); Connected += AbsoluteConnector_Connected; _messageTimer = new ThreadTimer(MessageTimerElapsed, TimeSpan.FromMilliseconds(500)); _messageTimer.Start(ThreadPriority.Normal); }
/// <summary> /// Инициализация переменных. /// </summary> public void Init() { Version = "v1.21.14"; InitTime = DateTime.Now; varXml = new VarXml("Config.xml"); varXml.LoadFromXML(); CollectionWithUnits = new XPCollectionWithUnits(); DataSourceCollection = (CollectionWithUnits.Add(typeof(DataSource))).Collection; StatisticsCollection = (CollectionWithUnits.Add(typeof(Statistics))).Collection; OPCServerCollection = (CollectionWithUnits.Add(typeof(OPCServer))).Collection; VzljotCollection = (CollectionWithUnits.Add(typeof(Vzljot))).Collection; DDEServerCollection = (CollectionWithUnits.Add(typeof(DDEServer))).Collection; TechnographCollection = (CollectionWithUnits.Add(typeof(Technograph))).Collection; PingServerCollection = (CollectionWithUnits.Add(typeof(PingServer))).Collection; KMAZSServerCollection = (CollectionWithUnits.Add(typeof(KMAZSServer))).Collection; ItemCollection = (CollectionWithUnits.Add(typeof(Item))).Collection; SQLServerCollection = (CollectionWithUnits.Add(typeof(SQLServer))).Collection; SQLServerItemForceCollection = (CollectionWithUnits.Add(typeof(SQLServerItemForceCollection))).Collection; DataSourceRealCollection = new CollectionEx <DataSourceReal>(); StatisticsRealCollection = new CollectionEx <StatisticsReal>(); OPCServerRealCollection = new CollectionEx <OPCServerReal>(); VzljotRealCollection = new CollectionEx <VzljotReal>(); DDEServerRealCollection = new CollectionEx <DDEServerReal>(); TechnographRealCollection = new CollectionEx <TechnographReal>(); PingServerRealCollection = new CollectionEx <PingServerReal>(); KMAZSServerRealCollection = new CollectionEx <KMAZSServerReal>(); ItemRealCollection = new Collection <ItemReal>(); SQLServerRealCollection = new CollectionEx <SQLServerReal>(); CopyDataToReal(); ThreadMainFautCount = 0; ThreadMain = new ThreadTimer() { Period = varXml.ThreadMainPeriod }; ThreadMain.WorkChanged += ThreadMain_WorkChanged; ThreadMain.Run(); ThreadMainDelay = varXml.ThreadMainDelay; AppName = varXml.AppName; WorkerReboot = new BackgroundWorker(); WorkerReboot.DoWork += WorkerReboot_DoWork; }
/// <summary> /// Stops ping / pong operation and releases all resources /// </summary> public void Stop() { if (_timer != null) { _timer.Stop(); _timer = null; } _clients.Clear(); lock (_incoming) _incoming.Clear(); lock (_outgoing) _outgoing.Clear(); }
private void MainLoop() { StreamInitialized(); ThreadTimer.Start(); #if !DEBUG try { #endif while (!Token.IsCancellationRequested) { while (Device.WriteWResult(MagicPacket) != MagicPacket.Length) { Console.WriteLine($"Warning: Couldn't write data to device ({Kind} thread)"); System.Threading.Thread.Sleep(1000); Device.Flush(); } var size = ReadNextPacket(); if (size > MaxBufSize || size <= 0) { Console.WriteLine($"Warning: Discarding packet of size {size} ({Kind} thread)"); System.Threading.Thread.Sleep(500); Device.Flush(); } else { Target.SendData(Data, 0, (int)size); #if PRINT_DEBUG Console.WriteLine($"video {size}"); #endif TransfersPerSecond++; BytesPerSecond += size; CheckPlayStats(); } } #if !DEBUG } catch (Exception ex) { Console.WriteLine("There was an exception: " + ex.ToString()); } #endif Console.WriteLine($"{Kind} thread stopped."); }
protected override void OnShown(EventArgs e) { base.OnShown(e); Exchange.Connect(); InitializeBaseCurrencies(); UpdateTickersAccordingBaseCurrency(); HasShown = true; UpdateSelectedTickersFromExchange(); if (!Exchange.SupportWebSocket(WebSocketType.Tickers)) { ThreadTimer.InitializeLifetimeService(); SetInfoConnected(); } else { Exchange.TickerChanged += OnWebSocketTickerUpdate; Exchange.TickersUpdate += OnWebSocketTickersUpdate; SubscribeWebSocket(); } }
/// <summary> /// 构造函数:指定同步间隔时间及所有数据同步的委托,只适合那种更新较快的项 /// 通过定时表达式创建定时激活器 /// 定时器设置格式如下: /// 1、定时触发:0|h|1,表示按每小时激活,0|m|1 表示按每分钟激活,0|s|1 表示按每秒钟激活,0|ms|1 表示按每毫秒激活 /// 2、时点触发:1|17:30;17:12;02:36 /// </summary> /// <param name="GapSpanExp"></param> /// <returns></returns> internal CacheItem(string GapSpanExp, Func <Dictionary <TKey, TValue> > method, Dictionary <TKey, TValue> items) { GetAllMethod = method; if (items != null) { myCacheItem = CacheItemInfoCollection <TParam, TKey, TValue> .CreateDatas(items); } else { myCacheItem = new CacheItemInfoCollection <TParam, TKey, TValue>(); } myCacheItem.Owner = this; ThreadTimer timer = ThreadTimer.CreateThreadTimerByExp(GapSpanExp); timer.Method = SyncData; syncUtil = new ThreadSvrUtil(timer); //自动启动同步服务 syncUtil.Start(); }
/// <summary> /// Starts shrink timer /// </summary> internal void Start(TimeSpan interval) { if (_autoShrinkTimer != null) { Stop(); } _autoShrinkTimer = new ThreadTimer(async() => { if (_shrinking) { return; } if (ShrinkRequired) { await _database.Shrink(); } }, interval); _autoShrinkTimer.Start(ThreadPriority.BelowNormal); }
/// <summary> /// Starts the connector and connects to the server /// </summary> public override void Run() { _running = true; if (_timer != null) { return; } _timer = new ThreadTimer(() => { if (!IsRunning) { _timer.Stop(); _timer = null; return; } if (NeedReconnect() && !_connecting) { try { _connecting = true; Connect(); } catch (Exception ex) { RaiseException(ex); } finally { _connecting = false; } } }, Interval); _timer.Start(ThreadPriority.BelowNormal); }
public void Run_WorkCount_Empty() { int realWorkCount = 0; EventHandler workChangedHandler = (sender, e) => { realWorkCount++; }; ThreadTimer threadTimer = new ThreadTimer(); threadTimer.Period = 100; threadTimer.Delay = 10; threadTimer.WorkChanged += workChangedHandler; threadTimer.Run(); Thread.Sleep(1000); Console.WriteLine(string.Format("realWorkCount = {0}; threadTimer.WorkCount = {1}, cycleCount = {2}", realWorkCount, threadTimer.WorkCount, threadTimer.CycleCount)); Assert.IsTrue(realWorkCount != 0 && realWorkCount == threadTimer.WorkCount && 9 <= realWorkCount && realWorkCount <= 11 && threadTimer.CycleCount >= 60); }
/// <summary> /// Starts to ping connected clients /// </summary> public void Start() { _timer = new ThreadTimer(Tick, TIMER_INTERVAL); _timer.Start(ThreadPriority.Lowest); }
/// <summary> /// Starts to follow messages /// </summary> public void Run() { _timer = new ThreadTimer(CheckExpirations, TimeSpan.FromMilliseconds(1000)); _timer.Start(ThreadPriority.BelowNormal); }
private void MainLoop() { Target.ClientConnected += StreamInitialized; Target.InitializeStreaming(); ThreadTimer.Start(); #if BENCHMARK Stopwatch benchmark = new Stopwatch(); #endif #if !DEBUG try { #endif while (!Token.IsCancellationRequested) { #if BENCHMARK benchmark.Restart(); #endif bool ShouldBlock = false; lock (wait) ShouldBlock = SuspendThread; if (ShouldBlock) { wait.WaitOne(); } while (Device.WriteWResult(MagicPacket) != MagicPacket.Length) { Console.WriteLine($"Warning: Couldn't write data to device ({Kind} thread)"); System.Threading.Thread.Sleep(1000); Device.Flush(); } var size = ReadNextPacket(); if (size > MaxBufSize || size <= 0) { Console.WriteLine($"Warning: Discarding packet of size {size} ({Kind} thread)"); System.Threading.Thread.Sleep(500); Device.Flush(); } else { Target.SendData(Data, 0, (int)size, Timestamp); #if LOG Console.WriteLine($"video {size}"); #endif TransfersPerSecond++; BytesPerSecond += size; CheckPlayStats(); } #if BENCHMARK if (Kind == StreamKind.Video) { Console.WriteLine(benchmark.ElapsedMilliseconds); } #endif } #if !DEBUG } catch (Exception ex) { if (!Token.IsCancellationRequested) { Console.WriteLine("There was an exception: " + ex.ToString()); } } #endif Console.WriteLine($"{Kind} thread stopped."); }