/// <summary> /// Tries to connect to the QDMS server. /// </summary> public void Connect() { if (ClientRunningAndIsConnected) { return; } lock (realTimeRequestSocketLock) { if (CreateRealTimeRequestSocket()) { return; } } lock (realTimeDataSocketLock) { realTimeDataSocket = new SubscriberSocket(realTimeDataConnectionString); realTimeDataSocket.Options.Identity = Encoding.UTF8.GetBytes(name); realTimeDataSocket.ReceiveReady += RealTimeDataSocketReceiveReady; } lock (historicalDataSocketLock) { historicalDataSocket = new DealerSocket(historicalDataConnectionString); historicalDataSocket.Options.Identity = Encoding.UTF8.GetBytes(name); historicalDataSocket.ReceiveReady += HistoricalDataSocketReceiveReady; } lastHeartBeat = DateTime.Now; heartBeatTimer = new NetMQTimer(TimeSpan.FromSeconds(HeartBeatPeriodInSeconds)); heartBeatTimer.Elapsed += HeartBeatTimerElapsed; historicalDataTimer = new NetMQTimer(TimeSpan.FromSeconds(HistoricalDataRequestsPeriodInSeconds)); historicalDataTimer.Elapsed += HistoricalDataTimerElapsed; poller = new NetMQPoller { realTimeRequestSocket, realTimeDataSocket, historicalDataSocket, heartBeatTimer, historicalDataTimer }; poller.RunAsync(); }
public void RemoveTimer() { using (var context = NetMQContext.Create()) using (var router = context.CreateRouterSocket()) using (var dealer = context.CreateDealerSocket()) using (var poller = new Poller(router) { PollTimeout = TestPollTimeoutMillis }) { int port = router.BindRandomPort("tcp://127.0.0.1"); dealer.Connect("tcp://127.0.0.1:" + port); bool timerTriggered = false; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(100)); timer.Elapsed += (a, s) => { timerTriggered = true; }; // The timer will fire after 100ms poller.AddTimer(timer); bool messageArrived = false; router.ReceiveReady += (s, e) => { router.SkipFrame(); router.SkipFrame(); messageArrived = true; // Remove timer poller.RemoveTimer(timer); }; poller.PollTillCancelledNonBlocking(); Thread.Sleep(20); dealer.Send("hello"); Thread.Sleep(300); poller.CancelAndJoin(); Assert.IsTrue(messageArrived); Assert.IsFalse(timerTriggered); } }
/// <summary> /// /// </summary> public MasterServer() { m_client = new DealerSocket(); m_client.Options.Linger = TimeSpan.Zero; m_client.ReceiveReady += ClientReceive; m_receiveTimer = Stopwatch.StartNew(); var sendTimer = new NetMQTimer(SEND_INTERVAL); sendTimer.Elapsed += SendQueue; m_poller = new NetMQPoller { sendTimer, m_client }; //m_poller.PollTimeout = 10; }
public void SubmitLogs() { try { var timer = new NetMQTimer(TimeSpan.FromSeconds(1)); timer.Elapsed += (s, e1) => { if (_SubmitCTS.IsCancellationRequested) { e1.Timer.Enable = false; return; } if (LogDtos.Count > 0) { LogDto logDto = new LogDto(); for (int i = 0; i < LogDtos.Count; i++) { var isGet = LogDtos.TryDequeue(out logDto); if (isGet) { if (logDto.LogType == LiveStateType.Pushing) { LogHelper.SetLogInfo($"{logDto.LogContent}=={logDto.Id} =={logDto.LogType}"); } else { LogHelper.SetLogError($"{logDto.LogContent}=={logDto.Id} =={logDto.LogType}"); } _SubmitMQService.RequestSendCommandLog(logDto); } } } }; using (var poller = new NetMQPoller { timer }) { poller.Run(); } } catch (Exception ex) { LogHelper.SetLogError($"服务日志:{ex.ToString()}"); } }
public void RemoveTimer() { using (var router = new RouterSocket()) using (var dealer = new DealerSocket()) using (var poller = new NetMQPoller { router }) { int port = router.BindRandomPort("tcp://127.0.0.1"); dealer.Connect("tcp://127.0.0.1:" + port); bool timerTriggered = false; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(100)); timer.Elapsed += (s, a) => { timerTriggered = true; }; // The timer will fire after 100ms poller.Add(timer); bool messageArrived = false; router.ReceiveReady += (s, e) => { router.SkipFrame(); router.SkipFrame(); messageArrived = true; // Remove timer poller.Remove(timer); }; poller.RunAsync(); Thread.Sleep(20); dealer.SendFrame("hello"); Thread.Sleep(300); poller.Stop(); Assert.IsTrue(messageArrived); Assert.IsFalse(timerTriggered); } }
public void ResetTimer() { using (NetMQContext context = NetMQContext.Create()) { const int timerIntervalMillis = 50; var timer1 = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)); var timer2 = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis / 2)); int count = 0; timer1.Elapsed += (a, s) => { count++; }; timer2.Elapsed += (sender, args) => { timer1.EnableAndReset(); timer2.Enable = false; }; using (var poller = new Poller(timer1, timer2) { PollTimeout = TestPollTimeoutMillis }) { poller.PollTillCancelledNonBlocking(); Thread.Sleep((int)(timerIntervalMillis * 1.1)); // it shouldn't have run Assert.AreEqual(0, count); Thread.Sleep((int)(timerIntervalMillis * 0.5)); // it should have run once Assert.AreEqual(1, count); poller.CancelAndJoin(); } } }
/// <summary> /// run the broker - if not bound to endpoint automatically binds to known endpoint /// </summary> /// <param name="token">CancellationToken to cancel the method</param> /// <exception cref="InvalidOperationException">Can't start same broker more than once!</exception> public void RunSynchronous(CancellationToken token) { if (m_isRunning) { throw new InvalidOperationException("Can't start same broker more than once!"); } if (!m_isBound) { Bind(); } m_isRunning = true; using (var poller = new NetMQPoller()) { Socket.ReceiveReady += ProcessReceivedMessage; // get timer for scheduling heartbeat var timer = new NetMQTimer(HeartbeatInterval); // send every 'HeartbeatInterval' a heartbeat to all not expired workers timer.Elapsed += (s, e) => SendHeartbeat(); poller.Add(Socket); poller.Add(timer); Log("Starting to listen for incoming messages ..."); // start the poller and wait for the return, which will happen once token is // signalling Cancel(!) Task.Factory.StartNew(poller.Run, token).Wait(); Log("... Stopped!"); // clean up poller.Remove(timer); poller.Remove(Socket); // unregister event handler Socket.ReceiveReady -= ProcessReceivedMessage; } m_isRunning = false; }
private void Run(PairSocket shim) { using (_publisherSocket = new PublisherSocket(_address)) { //_publisherSocket.Bind(_address); //_publisherSocket.ReceiveReady += DropPublisherSubscriptions; shim.ReceiveReady += OnShimMessage; _heartbeatTimer = new NetMQTimer(TimeSpan.FromSeconds(10)); _heartbeatTimer.Elapsed += OnHeartbeatTimerElapsed; // signal the actor that the shim is ready to work shim.SignalOK(); _poller = new NetMQPoller { shim, _publisherSocket, _heartbeatTimer }; _poller.Run(); } }
public void Start() { Initialize(); if (IsRunning) { return; } _beacon.Subscribe(""); _beacon.Publish(_selfNode.Serialize(), TimeSpan.FromSeconds(1)); timer = new NetMQTimer(TimeSpan.FromSeconds(1)); timer.Elapsed += ClearDeadNodes; _poller = new NetMQPoller { _beacon, timer }; _poller.RunAsync(); }
public override void Stop() { Logger.Write("Stopping"); if (Poller != null) { Logger.Write("Disabling timer"); HeartbeatTimer.Enable = false; Logger.Write("Removing timer"); Poller.Remove(HeartbeatTimer); Logger.Write("Setting timer to null"); HeartbeatTimer = null; Logger.Write("Stopping poller"); Poller.Stop(); Logger.Write("Setting poller to null"); Poller = null; } Logger.Write("Base stop to clean up socket"); base.Stop(); }
static void Main(string[] args) { using (var context = NetMQContext.Create()) { string[] topics = new string[] { "A", "B", "C" }; Random random = new Random(); using (var publisher = context.CreateXPublisherSocket()) { // Set publisher to manual subscriptions mode publisher.Options.ManualPublisher = true; publisher.Bind("tcp://*:5556"); publisher.ReceiveReady += (sender, eventArgs) => { var message = publisher.ReceiveString(); // we only handle subscription requests, unsubscription and any // other type of messages will be dropped if (message[0] == (char)1) { // calling Subscribe to add subscription to the last subscriber publisher.Subscribe(message.Substring(1)); } }; NetMQTimer sendTimer = new NetMQTimer(1000); sendTimer.Elapsed += (sender, eventArgs) => { // sends a message every second with random topic and current time publisher. SendMore(topics[random.Next(3)]). Send(DateTime.Now.ToString()); }; Poller poller = new Poller(); poller.AddSocket(publisher); poller.AddTimer(sendTimer); poller.PollTillCancelled(); } } }
public void TwoTimers() { var timer1 = new NetMQTimer(TimeSpan.FromMilliseconds(52)); var timer2 = new NetMQTimer(TimeSpan.FromMilliseconds(40)); int count = 0; int count2 = 0; var signal1 = new ManualResetEvent(false); var signal2 = new ManualResetEvent(false); timer1.Elapsed += (a, s) => { count++; timer1.Enable = false; timer2.Enable = false; signal1.Set(); }; timer2.Elapsed += (s, e) => { count2++; signal2.Set(); }; using (var poller = new Poller(timer1, timer2) { PollTimeout = TestPollTimeoutMillis }) { poller.PollTillCancelledNonBlocking(); Assert.IsTrue(signal1.WaitOne(300)); Assert.IsTrue(signal2.WaitOne(300)); poller.CancelAndJoin(); } Assert.AreEqual(1, count); Assert.AreEqual(1, count2); }
public void TwoTimers() { using (NetMQContext contex = NetMQContext.Create()) { Poller poller = new Poller(); int count = 0; NetMQTimer timer = new NetMQTimer(TimeSpan.FromMilliseconds(50)); NetMQTimer timer2 = new NetMQTimer(TimeSpan.FromMilliseconds(24)); timer.Elapsed += (a, s) => { count++; if (count == 3) { timer.Enable = false; timer2.Enable = false; } }; poller.AddTimer(timer); int count2 = 0; timer2.Elapsed += (s, a) => { count2++; }; poller.AddTimer(timer2); Task.Factory.StartNew(poller.Start); Thread.Sleep(300); poller.Stop(); Assert.AreEqual(3, count); Assert.AreEqual(6, count2); } }
public void Start() { _worker.ReceiveReady += _worker_ReceiveReady; _worker.Connect("tcp://localhost:5556"); _heartbeatTimer = new NetMQTimer(Paranoid.HEARTBEAT_INTERVAL_MS); _heartbeatTimer.Elapsed += heartbeatTimer_Elapsed; _poller = new Poller(); _poller.AddSocket(_worker); _poller.AddTimer(_heartbeatTimer); _scheduler = new NetMQScheduler(_context, _poller); _nextHeartbeatAt = DateTime.Now.AddMilliseconds(Paranoid.HEARTBEAT_INTERVAL_MS); _cylces = 0; Task.Factory.StartNew(() => Run(), TaskCreationOptions.LongRunning); SendReady(); }
public async Task Start() { _server.Bind(_localConnectionString); _poller.Add(_server); _poller.RunAsync(); foreach (var connStr in _peerConnectionStrings) { DealerSocket peer = new DealerSocket(); peer.Options.Identity = _nodeId.ToByteArray(); peer.ReceiveReady += Peer_ReceiveReady; peer.Connect(connStr); _poller.Add(peer); peer.SendFrame(ConvertOp(MessageOp.Ping)); } _houseKeeper = new NetMQTimer(TimeSpan.FromSeconds(30)); _houseKeeper.Elapsed += HouseKeeper_Elapsed; _poller.Add(_houseKeeper); _houseKeeper.Enable = true; }
/// <summary> /// create worker with standard parameter /// HeartbeatDelay == 2500 milliseconds /// ReconnectDelay == 2500 milliseconds /// ConnectionRetries == 3 /// Verbose == false /// </summary> private MDPWorker() { HeartbeatDelay = TimeSpan.FromMilliseconds(2500); ReconnectDelay = TimeSpan.FromMilliseconds(2500); m_timer = new NetMQTimer(HeartbeatDelay); m_timer.Enable = false; m_timer.Elapsed += (s, e) => OnHeartbeat(); m_pollerQueue = new NetMQQueue <Action>(); m_pollerQueue.ReceiveReady += (sender, args) => { var action = args.Queue.Dequeue(); action.Invoke(); }; m_poller = new NetMQPoller(); m_poller.Add(m_pollerQueue); m_poller.Add(m_timer); m_poller.RunAsync(); }
public void TwoTimers() { var timer1 = new NetMQTimer(TimeSpan.FromMilliseconds(52)); var timer2 = new NetMQTimer(TimeSpan.FromMilliseconds(40)); int count = 0; int count2 = 0; var signal1 = new ManualResetEvent(false); var signal2 = new ManualResetEvent(false); timer1.Elapsed += (s, a) => { count++; timer1.Enable = false; timer2.Enable = false; signal1.Set(); }; timer2.Elapsed += (s, e) => { count2++; signal2.Set(); }; using (var poller = new NetMQPoller { timer1, timer2 }) { poller.RunAsync(); Assert.IsTrue(signal1.WaitOne(300)); Assert.IsTrue(signal2.WaitOne(300)); poller.Stop(); } Assert.AreEqual(1, count); Assert.AreEqual(1, count2); }
private void StratListen(int milliseconds = NetmqOptions.PolicyMillisecond) { Task.Factory.StartNew((par) => { var listen = par as List <PublisherListen>; NetMQTimer netMQTimer = new NetMQTimer(milliseconds); netMQTimer.Elapsed += (a, b) => { foreach (var item in listen) { //检测发送的命令是否收到客户端回复 没有则持续发送出去 if (item.IsSendListens()) { Publish(item.Topic, item.SendData); } else { //检测客户端是否断网 down 机了 if (item.IsListensServiceError()) { var objdata = item.SendData as CommandDto; OnResponseReceivePushEvent(new LogDto() { LogType = LiveStateType.ServiceError, ChanneId = objdata.ChanneId }); item.SendWebClientDate = DateTime.Now; } } } ChannelOperation(); }; using (var poller = new NetMQPoller() { netMQTimer }) { poller.Run(); } }, _publisherListens); }
public void TwoTimers() { using (NetMQContext contex = NetMQContext.Create()) using (Poller poller = new Poller()) { int count = 0; NetMQTimer timer = new NetMQTimer(TimeSpan.FromMilliseconds(52)); NetMQTimer timer2 = new NetMQTimer(TimeSpan.FromMilliseconds(24)); timer.Elapsed += (a, s) => { count++; if (count == 3) { timer.Enable = false; timer2.Enable = false; } }; poller.AddTimer(timer); int count2 = 0; timer2.Elapsed += (s, a) => { count2++; }; poller.AddTimer(timer2); poller.PollTillCancelledNonBlocking(); Thread.Sleep(300); poller.CancelAndJoin(); Assert.AreEqual(3, count); Assert.AreEqual(6, count2); } }
public void Stop() { if (!IsRunning) { return; } this._nodes.Clear(); _poller.Stop(); _beacon.Unsubscribe(); _poller.Remove(_beacon); _poller.Remove(timer); _poller.Dispose(); _poller = null; _beacon.Dispose(); _beacon = null; timer = null; }
/// <summary> /// This method is being run asynchronously by m_actor. /// </summary> /// <param name="shim"></param> private void RunActor(PairSocket shim) { _pipe = shim; _pipe.ReceiveReady += OnPipeReceiveReady; var reapTimer = new NetMQTimer(TimeSpan.FromMilliseconds(1000)); reapTimer.Elapsed += OnReapTimerElapsed; // Start poller, but poll only the _pipe. Start() and Stop() will add/remove other items to poll _poller = new NetMQPoller { _pipe, reapTimer }; // Signal the actor that we're ready to work _pipe.SignalOK(); // polling until cancelled _poller.Run(); Dispose(); }
/// <summary> /// Create a new instance of a Proxy (NetMQ.Proxy) /// with the given sockets to serve as a front-end, a back-end, and a control socket. /// </summary> /// <param name="publisherAddress">the address that messages will be forwarded from</param> /// <param name="subscriberAddress">the address that messages should be sent to</param> /// <param name="heartbeat">the timespan at which to send HEARTBEAT messages (in milliseconds) - you can set this to zero if not needed</param> /// <param name="control">this socket will have messages also sent to it - you can set this to null if not needed</param> public ZeroMqHub(string publisherAddress, string subscriberAddress, int heartbeat = 0, NetMQSocket control = null) { _subscriberAddress = subscriberAddress; _publisherAddress = publisherAddress; var context = NetMQContext.Create(); _subscriber = context.CreateXSubscriberSocket(); _publisher = context.CreateXPublisherSocket(); _control = control; if (heartbeat > 0) { _heartbeat = new NetMQTimer(heartbeat); _heartbeat.Elapsed += (s, a) => _publisher.Send("HEARTBEAT"); } Name = "XPub-XSub"; PSJobTypeName = typeof(ZeroMqHub).Name; _subscriber.Bind(subscriberAddress); _publisher.Bind(publisherAddress); }
public void ResponseReceive(int Milliseconds = NetmqOptions.ResopneMillisecond) { Task.Factory.StartNew((par) => { try { var listen = par as List <PublisherListen>; var isCancel = cancellationTokenSource.Token.IsCancellationRequested; var mqTime = new NetMQTimer(TimeSpan.FromMilliseconds(Milliseconds)); mqTime.Elapsed += (sender, e) => { if (isCancel) { e.Timer.Enable = false; return; } _netMQManage.ResponseReceive((a) => { //收到消息后进行回调处理业务,处理完后在 反馈消息出去 var request = JsonConvert.DeserializeObject <RequestData>(a); listen.ResultListens(request.Id); return(ResultResponse(request)); }); }; using (var poller = new NetMQPoller { mqTime }) { poller.Run(); } } catch (Exception ex) { LogWrite.Error(ex); } }, _publisherListens, cancellationTokenSource.Token); }
public void RunPipeline(PairSocket shim) { // we should signal before running the poller but this will block the application shim.SignalOK(); this.poller = new Poller(); shim.ReceiveReady += OnShimReady; poller.AddSocket(shim); timeoutTimer = new NetMQTimer(StreamingProtocol.Timeout); timeoutTimer.Elapsed += TimeoutElapsed; poller.AddTimer(timeoutTimer); Connect(); poller.Start(); if (subscriberSocket != null) { subscriberSocket.Dispose(); } }
private void Run(PairSocket shim) { _shim = shim; shim.ReceiveReady += OnShimMessage; _timeoutTimer = new NetMQTimer(_heartbeatTimeOut); _timeoutTimer.Elapsed += OnTimeoutTimer; _reconnectTimer = new NetMQTimer(_reconnectInterval); _reconnectTimer.Elapsed += OnReconnectTimer; _poller = new NetMQPoller { shim, _timeoutTimer, _reconnectTimer }; shim.SignalOK(); Connect(); _poller.Run(); _subscriber?.Dispose(); }
public void TestPollerDispose() { const int timerIntervalMillis = 10; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)); var signal = new ManualResetEvent(false); var count = 0; timer.Elapsed += (a, s) => { if (count++ == 5) { signal.Set(); } }; Poller poller; using (poller = new Poller(timer) { PollTimeout = TestPollTimeoutMillis }) { poller.PollTillCancelledNonBlocking(); Assert.IsTrue(signal.WaitOne(500)); Assert.IsTrue(poller.IsStarted); Assert.Throws <InvalidOperationException>(() => poller.PollTillCancelled()); } Assert.IsFalse(poller.IsStarted); Assert.Throws <ObjectDisposedException>(() => poller.PollTillCancelled()); Assert.Throws <ObjectDisposedException>(() => poller.CancelAndJoin()); Assert.Throws <ObjectDisposedException>(() => poller.AddTimer(timer)); Assert.Throws <ObjectDisposedException>(() => poller.RemoveTimer(timer)); }
public void TestPollerDispose() { const int timerIntervalMillis = 10; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)); var signal = new ManualResetEvent(false); var count = 0; timer.Elapsed += (s, a) => { if (count++ == 5) { signal.Set(); } }; NetMQPoller poller; using (poller = new NetMQPoller { timer }) { poller.RunAsync(); Assert.IsTrue(signal.WaitOne(500)); Assert.IsTrue(poller.IsRunning); Assert.Throws <InvalidOperationException>(() => poller.Run()); } Assert.IsFalse(poller.IsRunning); Assert.Throws <ObjectDisposedException>(() => poller.Run()); Assert.Throws <ObjectDisposedException>(() => poller.Stop()); Assert.Throws <ObjectDisposedException>(() => poller.Add(timer)); Assert.Throws <ObjectDisposedException>(() => poller.Remove(timer)); }
/// <summary> /// setup the client with standard values /// verbose == false /// Connect the client to broker /// </summary> private MDPClientAsync() { m_client = null; m_connected = false; m_currentBrokerIndex = -1; // TODO use random!? m_pollerQueue = new NetMQQueue <Action>(); m_pollerQueue.ReceiveReady += (sender, args) => OnAction(args); m_requestQueue = new RequestsQueue(); m_requestQueue.FailedRequest += (s, e) => OnFailedRequest(e); m_poller = new NetMQPoller(); Timeout = m_defaultTimeOut; m_timer = new NetMQTimer(m_purgeCheckTime); m_timer.Enable = false; m_timer.Elapsed += (s, e) => OnPurgeRequest(); m_poller.Add(m_timer); m_poller.Add(m_pollerQueue); m_poller.Add(m_timer); m_poller.RunAsync(); }
private void Run(PairSocket shim) { using (_publisherSocket = new XPublisherSocket()) { _publisherSocket.SetWelcomeMessage(WelcomeMessage); _publisherSocket.Bind(_address); _publisherSocket.ReceiveReady += DropPublisherSubscriptions; _heartbeatTimer = new NetMQTimer(_heartbeatInterval); _heartbeatTimer.Elapsed += OnHeartbeatTimerElapsed; shim.ReceiveReady += OnShimMessage; // signal the actor that the shim is ready to work shim.SignalOK(); _poller = new NetMQPoller { _publisherSocket, shim, _heartbeatTimer }; // Polling until poller is cancelled _poller.Run(); } }
public ZmqSocketFactory(NetMQContext context, Poller poller = null) { if (context == null) { throw new ArgumentNullException("context"); } if (poller == null) { _poller = new Poller(); var thread = new Thread(pol => ((Poller)pol).Start()); thread.Start(_poller); } else { _poller = poller; } _context = context; _timer = new NetMQTimer(0) { Enable = true }; _timer.Elapsed += OnTimer; _poller.AddTimer(_timer); }
public void PollOnce() { int count = 0; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(50)); timer.Elapsed += (a, s) => { count++; if (count == 3) { timer.Enable = false; } }; // NOTE if the PollTimeout here is less than the timer period, it won't fire during PollOnce -- is this by design? using (var poller = new Poller(timer) { PollTimeout = 1000 }) { Stopwatch stopwatch = Stopwatch.StartNew(); poller.PollOnce(); var pollOnceElapsedTime = stopwatch.ElapsedMilliseconds; Assert.AreEqual(1, count, "the timer should have fired just once during the call to PollOnce()"); Assert.Less(pollOnceElapsedTime, 90, "pollonce should return soon after the first timer firing."); } }
public void RemoveTimer() { using (var context = NetMQContext.Create()) using (var router = context.CreateRouterSocket()) using (var dealer = context.CreateDealerSocket()) using (var poller = new Poller(router) { PollTimeout = TestPollTimeoutMillis }) { int port = router.BindRandomPort("tcp://127.0.0.1"); dealer.Connect("tcp://127.0.0.1:" + port); bool timerTriggered = false; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(100)); timer.Elapsed += (a, s) => { timerTriggered = true; }; // The timer will fire after 100ms poller.AddTimer(timer); bool messageArrived = false; router.ReceiveReady += (s, e) => { router.SkipFrame(); router.SkipFrame(); messageArrived = true; // Remove timer poller.RemoveTimer(timer); }; poller.PollTillCancelledNonBlocking(); Thread.Sleep(20); dealer.SendFrame("hello"); Thread.Sleep(300); poller.CancelAndJoin(); Assert.IsTrue(messageArrived); Assert.IsFalse(timerTriggered); } }
public void TestPollerDispose() { const int timerIntervalMillis = 10; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)); var signal = new ManualResetEvent(false); var count = 0; timer.Elapsed += (s, a) => { if (count++ == 5) signal.Set(); }; NetMQPoller poller; using (poller = new NetMQPoller { timer }) { poller.RunAsync(); Assert.IsTrue(signal.WaitOne(500)); Assert.IsTrue(poller.IsRunning); Assert.Throws<InvalidOperationException>(() => poller.Run()); } Assert.IsFalse(poller.IsRunning); Assert.Throws<ObjectDisposedException>(() => poller.Run()); Assert.Throws<ObjectDisposedException>(() => poller.Stop()); Assert.Throws<ObjectDisposedException>(() => poller.Add(timer)); Assert.Throws<ObjectDisposedException>(() => poller.Remove(timer)); }
public void ChangeTimerInterval() { int count = 0; const int timerIntervalMillis = 10; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)); var stopwatch = new Stopwatch(); long length1 = 0; long length2 = 0; timer.Elapsed += (s, a) => { count++; if (count == 1) { stopwatch.Start(); } else if (count == 2) { length1 = stopwatch.ElapsedMilliseconds; timer.Interval = 20; stopwatch.Restart(); } else if (count == 3) { length2 = stopwatch.ElapsedMilliseconds; stopwatch.Stop(); timer.Enable = false; } }; using (var poller = new NetMQPoller { timer }) { poller.RunAsync(); Thread.Sleep(timerIntervalMillis * 6); poller.Stop(); } Assert.AreEqual(3, count); Assert.AreEqual(10.0, length1, 2.0); Assert.AreEqual(20.0, length2, 2.0); }
public void ChangeTimerInterval() { using (NetMQContext contex = NetMQContext.Create()) using (Poller poller = new Poller()) { int count = 0; NetMQTimer timer = new NetMQTimer(TimeSpan.FromMilliseconds(10)); Stopwatch stopwatch = new Stopwatch(); long length1 = 0; long length2 = 0; timer.Elapsed += (a, s) => { count++; if (count == 1) { stopwatch.Start(); } else if (count == 2) { length1 = stopwatch.ElapsedMilliseconds; timer.Interval = 20; stopwatch.Restart(); } else if (count == 3) { length2 = stopwatch.ElapsedMilliseconds; stopwatch.Stop(); timer.Enable = false; } }; poller.AddTimer(timer); Task.Factory.StartNew(poller.Start); Thread.Sleep(500); poller.Stop(); Assert.AreEqual(3, count); Console.WriteLine("Length1:{0}, Length2:{1}", length1, length2); Assert.GreaterOrEqual(length1, 8); Assert.LessOrEqual(length1, 12); Assert.GreaterOrEqual(length2, 18); Assert.LessOrEqual(length2, 22); } }
public void ChangeTimerInterval() { int count = 0; const int timerIntervalMillis = 10; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)); var stopwatch = new Stopwatch(); long length1 = 0; long length2 = 0; timer.Elapsed += (a, s) => { count++; if (count == 1) { stopwatch.Start(); } else if (count == 2) { length1 = stopwatch.ElapsedMilliseconds; timer.Interval = 20; stopwatch.Restart(); } else if (count == 3) { length2 = stopwatch.ElapsedMilliseconds; stopwatch.Stop(); timer.Enable = false; } }; using (var poller = new Poller(timer) { PollTimeout = TestPollTimeoutMillis }) { poller.PollTillCancelledNonBlocking(); Thread.Sleep(timerIntervalMillis * 6); poller.CancelAndJoin(); } Assert.AreEqual(3, count); Assert.AreEqual(10.0, length1, 2.0); Assert.AreEqual(20.0, length2, 2.0); }
public void ResetTimer() { const int timerIntervalMillis = 50; var timer1 = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)); var timer2 = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis / 2)); int count = 0; timer1.Elapsed += (a, s) => { count++; }; timer2.Elapsed += (sender, args) => { timer1.EnableAndReset(); timer2.Enable = false; }; using (var poller = new Poller(timer1, timer2) { PollTimeout = TestPollTimeoutMillis }) { poller.PollTillCancelledNonBlocking(); Thread.Sleep((int)(timerIntervalMillis * 1.1)); // it shouldn't have run Assert.AreEqual(0, count); Thread.Sleep((int)(timerIntervalMillis * 0.5)); // it should have run once Assert.AreEqual(1, count); poller.CancelAndJoin(); } }
public void SimpleTimer() { // TODO it is not really clear what this test is actually testing -- maybe split it into a few smaller tests using (var router = new RouterSocket()) using (var dealer = new DealerSocket()) using (var poller = new NetMQPoller { router }) { int port = router.BindRandomPort("tcp://127.0.0.1"); dealer.Connect("tcp://127.0.0.1:" + port); bool messageArrived = false; router.ReceiveReady += (s, e) => { Assert.IsFalse(messageArrived); router.SkipFrame(); router.SkipFrame(); messageArrived = true; }; bool timerTriggered = false; int count = 0; const int timerIntervalMillis = 100; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)); timer.Elapsed += (s, a) => { // the timer should jump before the message Assert.IsFalse(messageArrived); timerTriggered = true; timer.Enable = false; count++; }; poller.Add(timer); poller.RunAsync(); Thread.Sleep(150); dealer.SendFrame("hello"); Thread.Sleep(300); poller.Stop(); Assert.IsTrue(messageArrived); Assert.IsTrue(timerTriggered); Assert.AreEqual(1, count); } }
public void RunMultipleTimes() { int count = 0; const int timerIntervalMillis = 20; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)); timer.Elapsed += (a, s) => { count++; if (count == 3) { timer.Enable = false; } }; using (var poller = new Poller(timer) { PollTimeout = TestPollTimeoutMillis }) { poller.PollTillCancelledNonBlocking(); Thread.Sleep(timerIntervalMillis * 6); poller.CancelAndJoin(); Assert.AreEqual(3, count); } }
public void TwoTimers() { using (NetMQContext contex = NetMQContext.Create()) using (Poller poller = new Poller()) { int count = 0; NetMQTimer timer = new NetMQTimer(TimeSpan.FromMilliseconds(50)); NetMQTimer timer2 = new NetMQTimer(TimeSpan.FromMilliseconds(24)); timer.Elapsed += (a, s) => { count++; if (count == 3) { timer.Enable = false; timer2.Enable = false; } }; poller.AddTimer(timer); int count2 = 0; timer2.Elapsed += (s, a) => { count2++; }; poller.AddTimer(timer2); Task.Factory.StartNew(poller.Start); Thread.Sleep(300); poller.Stop(); Assert.AreEqual(3, count); Assert.AreEqual(6, count2); } }
public void TestPollerDispose() { using (NetMQContext contex = NetMQContext.Create()) { int count = 0; NetMQTimer timer = new NetMQTimer(TimeSpan.FromMilliseconds(10)); Stopwatch stopwatch = new Stopwatch(); long length1 = 0; long length2 = 0; timer.Elapsed += (a, s) => { count++; if (count == 1) { stopwatch.Start(); } else if (count == 2) { length1 = stopwatch.ElapsedMilliseconds; timer.Interval = 20; stopwatch.Restart(); } else if (count == 3) { length2 = stopwatch.ElapsedMilliseconds; stopwatch.Stop(); timer.Enable = false; } }; Poller poller; using (poller = new Poller(timer)) { Task task = Task.Factory.StartNew(poller.Start); Thread.Sleep(500); Assert.Throws<InvalidOperationException>(() => { poller.Start(); }); } Assert.That(!poller.IsStarted); Assert.Throws<ObjectDisposedException>(() => { poller.Start(); }); Assert.Throws<ObjectDisposedException>(() => { poller.Stop(); }); Assert.Throws<ObjectDisposedException>(() => { poller.AddTimer(timer); }); Assert.Throws<ObjectDisposedException>(() => { poller.RemoveTimer(timer); }); Assert.AreEqual(3, count); Console.WriteLine("Length1:{0}, Length2:{1}", length1, length2); Assert.GreaterOrEqual(length1, 8); Assert.LessOrEqual(length1, 12); Assert.GreaterOrEqual(length2, 18); Assert.LessOrEqual(length2, 22); } }
public void SimpleTimer() { using (NetMQContext contex = NetMQContext.Create()) { // we are using three responses to make sure we actually move the correct socket and other sockets still work using (var router = contex.CreateRouterSocket()) { router.Bind("tcp://127.0.0.1:5002"); using (var dealer = contex.CreateDealerSocket()) using (Poller poller = new Poller()) { dealer.Connect("tcp://127.0.0.1:5002"); bool messageArrived = false; router.ReceiveReady += (s, a) => { bool isMore; router.Receive(out isMore); router.Receive(out isMore); messageArrived = true; }; poller.AddSocket(router); bool timerTriggered = false; int count = 0; NetMQTimer timer = new NetMQTimer(TimeSpan.FromMilliseconds(100)); timer.Elapsed += (a, s) => { // the timer should jump before the message Assert.IsFalse(messageArrived); timerTriggered = true; timer.Enable = false; count++; }; poller.AddTimer(timer); Task.Factory.StartNew(poller.Start); Thread.Sleep(150); dealer.Send("hello"); Thread.Sleep(300); poller.Stop(); Assert.IsTrue(messageArrived); Assert.IsTrue(timerTriggered); Assert.AreEqual(1, count); } } } }
public void EnableTimer() { const int timerIntervalMillis = 20; var timer1 = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)); var timer2 = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)) { Enable = false}; int count = 0; int count2 = 0; timer1.Elapsed += (a, s) => { count++; if (count == 1) { timer2.Enable = true; timer1.Enable = false; } else if (count == 2) { timer1.Enable = false; } }; timer2.Elapsed += (s, e) => { timer1.Enable = true; timer2.Enable = false; count2++; }; using (var poller = new Poller(timer1, timer2) { PollTimeout = TestPollTimeoutMillis }) { poller.PollTillCancelledNonBlocking(); Thread.Sleep(timerIntervalMillis * 6); poller.CancelAndJoin(); } Assert.AreEqual(2, count); Assert.AreEqual(1, count2); }
public void SimpleTimer() { // TODO it is not really clear what this test is actually testing -- maybe split it into a few smaller tests using (var context = NetMQContext.Create()) using (var router = context.CreateRouterSocket()) using (var dealer = context.CreateDealerSocket()) using (var poller = new Poller(router) { PollTimeout = TestPollTimeoutMillis }) { int port = router.BindRandomPort("tcp://127.0.0.1"); dealer.Connect("tcp://127.0.0.1:" + port); bool messageArrived = false; router.ReceiveReady += (s, a) => { Assert.IsFalse(messageArrived); router.Receive(); router.Receive(); messageArrived = true; }; bool timerTriggered = false; int count = 0; const int timerIntervalMillis = 100; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)); timer.Elapsed += (a, s) => { // the timer should jump before the message Assert.IsFalse(messageArrived); timerTriggered = true; timer.Enable = false; count++; }; poller.AddTimer(timer); poller.PollTillCancelledNonBlocking(); Thread.Sleep(150); dealer.Send("hello"); Thread.Sleep(300); poller.CancelAndJoin(); Assert.IsTrue(messageArrived); Assert.IsTrue(timerTriggered); Assert.AreEqual(1, count); } }
public void RunMultipleTimes() { int count = 0; const int timerIntervalMillis = 20; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)); timer.Elapsed += (s, a) => { count++; if (count == 3) { timer.Enable = false; } }; using (var poller = new NetMQPoller { timer }) { poller.RunAsync(); Thread.Sleep(timerIntervalMillis * 6); poller.Stop(); Assert.AreEqual(3, count); } }
public void TestPollerDispose() { const int timerIntervalMillis = 10; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)); var signal = new ManualResetEvent(false); var count = 0; timer.Elapsed += (a, s) => { if (count++ == 5) signal.Set(); }; Poller poller; using (poller = new Poller(timer) { PollTimeout = TestPollTimeoutMillis }) { poller.PollTillCancelledNonBlocking(); Assert.IsTrue(signal.WaitOne(500)); Assert.IsTrue(poller.IsStarted); Assert.Throws<InvalidOperationException>(() => poller.PollTillCancelled()); } Assert.IsFalse(poller.IsStarted); Assert.Throws<ObjectDisposedException>(() => poller.PollTillCancelled()); Assert.Throws<ObjectDisposedException>(() => poller.CancelAndJoin()); Assert.Throws<ObjectDisposedException>(() => poller.AddTimer(timer)); Assert.Throws<ObjectDisposedException>(() => poller.RemoveTimer(timer)); }
public void EnableTimer() { using (NetMQContext contex = NetMQContext.Create()) { Poller poller = new Poller(); int count = 0; NetMQTimer timer = new NetMQTimer(TimeSpan.FromMilliseconds(20)); NetMQTimer timer2 = new NetMQTimer(TimeSpan.FromMilliseconds(20)); timer.Elapsed += (a, s) => { count++; if (count == 1) { timer2.Enable = true; timer.Enable = false; } else if (count == 2) { timer.Enable = false; } }; int count2 = 0; timer2.Elapsed += (s, a) => { timer.Enable = true; timer2.Enable = false; count2++; }; timer2.Enable = false; poller.AddTimer(timer); poller.AddTimer(timer2); Task.Factory.StartNew(poller.Start); Thread.Sleep(300); poller.Stop(); Assert.AreEqual(2, count); Assert.AreEqual(1, count2); } }
/// <summary> /// This method is being run asynchronously by m_actor. /// </summary> /// <param name="shim"></param> private void RunActor(PairSocket shim) { _pipe = shim; _pipe.ReceiveReady += OnPipeReceiveReady; var reapTimer = new NetMQTimer(TimeSpan.FromMilliseconds(1000)); reapTimer.Elapsed += OnReapTimerElapsed; // Start poller, but poll only the _pipe. Start() and Stop() will add/remove other items to poll _poller = new NetMQPoller { _pipe, reapTimer }; // Signal the actor that we're ready to work _pipe.SignalOK(); // polling until cancelled _poller.Run(); reapTimer.Enable = false; reapTimer.Elapsed -= OnReapTimerElapsed; }
public void EnableTimer() { const int timerIntervalMillis = 20; var timer1 = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)); var timer2 = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)) { Enable = false}; int count = 0; int count2 = 0; timer1.Elapsed += (s, a) => { count++; if (count == 1) { timer2.Enable = true; timer1.Enable = false; } else if (count == 2) { timer1.Enable = false; } }; timer2.Elapsed += (s, e) => { timer1.Enable = true; timer2.Enable = false; count2++; }; using (var poller = new NetMQPoller { timer1, timer2 }) { poller.RunAsync(); Thread.Sleep(timerIntervalMillis * 6); poller.Stop(); } Assert.AreEqual(2, count); Assert.AreEqual(1, count2); }