コード例 #1
0
        public override void IntializeMonitor()
        {
            _timerHelper             = new ThreadTimer($"{CategoryName}:{MonitorName ?? string.Empty}:{HeartBeatData.CounterName}");
            _timerHelper.TimerEvent += (timer, state) => OnHeartbeat(this);

            StartTimer(HeartBeatIntervalInSeconds);
        }
コード例 #2
0
 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);
 }
コード例 #3
0
        /// <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);
        }
コード例 #4
0
        public void CreateDisposeAfterStarting()
        {
            var timer = new ThreadTimer();

            timer.Start();
            timer.Dispose();
        }
コード例 #5
0
        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);
        }
コード例 #6
0
 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);
 }
コード例 #7
0
        /// <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);
        }
コード例 #8
0
        /// <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();
        }
コード例 #9
0
 public void StopTwice()
 {
     using (var timer = new ThreadTimer())
     {
         timer.Stop();
         timer.Stop();
     }
 }
コード例 #10
0
ファイル: ShrinkManager.cs プロジェクト: ciker/twino
 /// <summary>
 /// Stop shrink timer
 /// </summary>
 internal void Stop()
 {
     if (_autoShrinkTimer != null)
     {
         _autoShrinkTimer.Stop();
         _autoShrinkTimer = null;
     }
 }
コード例 #11
0
ファイル: TimerDispatcher.cs プロジェクト: nistec/MQueue
 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");
 }
コード例 #12
0
ファイル: TimerSyncDispatcher.cs プロジェクト: nistec/MQueue
 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");
 }
コード例 #13
0
        public override void IntializeMonitor()
        {
            _queue = new LoopQueue(_averagePeriod, AverageIntervalInMinutes);

            _threadTimer             = new ThreadTimer();
            _threadTimer.TimerEvent += (timer, state) => OnAverageTic(this);

            StartTimer(AverageIntervalInMinutes);
        }
コード例 #14
0
ファイル: TimerDispatcher.cs プロジェクト: nistec/MQueue
 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() });
 }
コード例 #15
0
        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);
        }
コード例 #16
0
ファイル: DataTransferManager.cs プロジェクト: FlsZen/LibAtem
        private void StartTimer()
        {
            _startTimer = new ThreadTimer(() =>
            {
                if (_connection.HasTimedOut)
                {
                    return;
                }

                DequeueAndRun();
            }, AtemConstants.DataTransferCheckInterval);
        }
コード例 #17
0
        /// <summary>
        /// Destroys the queue time keeper.
        /// </summary>
        public async Task Destroy()
        {
            Reset();

            if (_timer != null)
            {
                _timer.Stop();
                _timer = null;
            }

            await Task.CompletedTask;
        }
コード例 #18
0
 /// <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;
 }
コード例 #19
0
        /// <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);
        }
コード例 #20
0
ファイル: Global.cs プロジェクト: vscode1111/DataToSQL
        /// <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;
        }
コード例 #21
0
        /// <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();
        }
コード例 #22
0
ファイル: StreamThread.cs プロジェクト: tzf-key/SysDVR
        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.");
        }
コード例 #23
0
 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();
     }
 }
コード例 #24
0
ファイル: CacheItem.cs プロジェクト: neao2002/RS.Core
        /// <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();
        }
コード例 #25
0
ファイル: ShrinkManager.cs プロジェクト: ciker/twino
        /// <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);
        }
コード例 #26
0
ファイル: StickyConnector.cs プロジェクト: Akrotiri/twino
        /// <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);
        }
コード例 #27
0
        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);
        }
コード例 #28
0
 /// <summary>
 /// Starts to ping connected clients
 /// </summary>
 public void Start()
 {
     _timer = new ThreadTimer(Tick, TIMER_INTERVAL);
     _timer.Start(ThreadPriority.Lowest);
 }
コード例 #29
0
 /// <summary>
 /// Starts to follow messages
 /// </summary>
 public void Run()
 {
     _timer = new ThreadTimer(CheckExpirations, TimeSpan.FromMilliseconds(1000));
     _timer.Start(ThreadPriority.BelowNormal);
 }
コード例 #30
0
        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.");
        }