private void CheckTimeouts()
        {
            LinkedListNode <ITimeout> node = list.First;

            if (node == null)
            {
                // Queue is empty.  Sleep until a new item is received.
                sleepInterval = int.MaxValue;
                return;
            }

            LinkedListNode <ITimeout> last = list.Last;

            while (node != null)
            {
                list.RemoveFirst();

                ITimeout command = node.Value;

                if (command.CheckTimeout())
                {
                    list.AddLast(command);
                }

                if (node == last)
                {
                    break;
                }
                node = list.First;
            }
        }
Пример #2
0
        public void Run(ITimeout timeout)
        {
            IChannel future = null;

            try
            {
                lock (lookobj)
                {
                    bootstrap.Handler(new DefaultChannelInitializer(handlers()));
                    future = bootstrap.ConnectAsync(this.endPoint).ConfigureAwait(false).GetAwaiter().GetResult();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            //如果重连失败,则调用ChannelInactive方法,再次出发重连事件,一直尝试12次,如果失败则不再重连
            if (future == null)
            {
                if (attempts <= reconnect)
                {
                    attempts++;
                    timer.NewTimeout(this, TimeSpan.FromMilliseconds(2 << attempts));
                }
            }
            else
            {
                Console.WriteLine("重连成功");
            }
        }
            public void Run(ITimeout timeout)
            {
                if (_timeoutHandler == null)
                {
                    return;
                }

                if (timeout.Canceled)
                {
                    return;
                }

                if (!clientChannel.NettyChannel.Open)
                {
                    return;
                }

                long currentTimeNanos = DateTime.UtcNow.Ticks;

                long timePassed     = currentTimeNanos - _timeoutHandler.LastMessageReceivedMilliseconds;
                long nextDelayMills = (_timeoutMilliseconds - timePassed) / 10000;

                if (nextDelayMills <= 0)
                {
                    clientChannel.OnReadTimeoutFired(request);
                }
                else
                {
                    request.ReadTimeout = (clientChannel._timer.NewTimeout(this, TimeSpan.FromMilliseconds(nextDelayMills)));
                }
            }
Пример #4
0
 private void DeleteExpirationTimer(ITimeout timeout)
 {
     if (timeout == null)
     {
         return;
     }
     timeout.Cancel();
 }
            public void Run(ITimeout timeout)
            {
                InvokeFuture future = conn.removeInvokeFuture(requestId);

                if (future != null)
                {
                    future.putResponse(outerInstance.commandFactory.createTimeoutResponse(conn.RemoteAddress));
                }
            }
Пример #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LogMerger"/> class using the specified
 /// NHibernate session factory.
 /// </summary>
 /// <param name="sessionFactory">A session factory configured to open sessions to the log
 /// database.</param>
 /// <param name="timeout">A timeout instance which will be used to trigger merges after new
 /// events arrive.</param>
 public LogMerger(ISessionFactory sessionFactory, ITimeout timeout)
 {
     if (sessionFactory == null)
         throw new ArgumentNullException("sessionFactory");
     if (timeout == null)
         throw new ArgumentNullException("timeout");
     this.sessionFactory = sessionFactory;
     this.timeout = timeout;
     this.timeout.Elapsed += TimedMerge;
 }
Пример #7
0
            public void Run(ITimeout timeout)
            {
                InvokeFuture future = conn.removeInvokeFuture(heartbeatId);

                if (future != null)
                {
                    future.putResponse(outerInstance.commandFactory.createTimeoutResponse(conn.RemoteAddress));
                    future.tryAsyncExecuteInvokeCallbackAbnormally();
                }
            }
Пример #8
0
        public void Run(ITimeout timeout)
        {
            var session = sessionMap.GetSessionOrDefault(context);

            if (session == null && config.ClientStatus != ClientStatus.CONNECT_CLOSE)
            {
                logger.Info("login timeout", context.Channel.ToString());
                context.Channel.CloseAsync();
            }
        }
 public void Run(ITimeout timeout)
 {
     try
     {
         var channel = bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(host), port)).GetAwaiter().GetResult();
     }
     catch (Exception e)
     {
         Console.WriteLine($"连接失败:{e}");
         Reconnect();
     }
 }
        public void TestScheduleTimeoutShouldRunAfterDelay()
        {
            ITimer   timer   = new HashedWheelTimer();
            var      barrier = new CountdownEvent(1);
            ITimeout timeout = timer.NewTimeout(
                new ActionTimerTask(
                    t => { barrier.Signal(); }),
                TimeSpan.FromSeconds(2));

            Assert.True(barrier.Wait(TimeSpan.FromSeconds(3)));
            Assert.True(timeout.Expired, "timer should expire");
            timer.StopAsync().Wait();
        }
 public void Run(ITimeout timeout)
 {
     channel.ExecuteInIoThread(new DelegateRunnable(() =>
     {
         try
         {
             timerTask.Run(timeout);
         }
         catch (Exception e)
         {
             channel.NettyChannel.Pipeline.FireExceptionCaught(e);
         }
     }));
 }
        private async Task CheckpointAsync(
            ITimeout timeout,
            IEventSourcedAggregateRoot aggregateRoot,
            CancellationToken token)
        {
            if (timeout.Canceled)
            {
                return;
            }

            await _checkpointManager.CheckpointAsync(aggregateRoot, token);

            timeout.Timer.NewTimeout(new FunctionTimerTask(async it => await CheckpointAsync(it, aggregateRoot, token)), TimeSpan.FromSeconds(_options.StepInSeconds));
        }
        public void Add(ITimeout command, int timeout)
        {
            queue.Enqueue(command);

            if (timeout < sleepInterval)
            {
                // Minimum sleep interval is 5ms.
                sleepInterval = (timeout >= 5)? timeout : 5;

                lock (this)
                {
                    cancel.Cancel();
                }
            }
        }
        public void TestScheduleTimeoutShouldNotRunBeforeDelay()
        {
            ITimer   timer   = new HashedWheelTimer(TimeSpan.FromMilliseconds(100), 512, -1);
            var      barrier = new CountdownEvent(1);
            ITimeout timeout = timer.NewTimeout(
                new ActionTimerTask(
                    t =>
            {
                Assert.True(false, "This should not have run");
                barrier.Signal();
            }),
                TimeSpan.FromSeconds(10));

            Assert.False(barrier.Wait(TimeSpan.FromSeconds(3)));
            Assert.False(timeout.Expired, "timer should not expire");
            timer.StopAsync().Wait();
        }
Пример #15
0
 public void Run(ITimeout timeout)
 {
     try
     {
         logger.Info($"reconnect start");
         var channel = bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(config.Ip), config.Port)).GetAwaiter().GetResult();
         var session = new Session(loggerFactory);
         session.Channel = channel;
         sessionMap.AddSession(session);
         logger.Info($"reconnect complete", channel.ToString());
     }
     catch (Exception e)
     {
         logger.Error($"reconnect exception", e);
         Reconnect();
     }
 }
Пример #16
0
        /// <summary>
        /// Invocation with callback.
        /// </summary>
        /// <param name="conn"> </param>
        /// <param name="request"> </param>
        /// <param name="invokeCallback"> </param>
        /// <param name="timeoutMillis"> </param>
        /// <exception cref="ThreadInterruptedException"> </exception>
        //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
        //ORIGINAL LINE: protected void invokeWithCallback(final Connection conn, final RemotingCommand request, final InvokeCallback invokeCallback, final int timeoutMillis)
        protected internal virtual void invokeWithCallback(Connection conn, RemotingCommand request, InvokeCallback invokeCallback, int timeoutMillis)
        {
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final InvokeFuture future = createInvokeFuture(conn, request, request.getInvokeContext(), invokeCallback);
            InvokeFuture future = createInvokeFuture(conn, request, request.InvokeContext, invokeCallback);

            conn.addInvokeFuture(future);
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final int requestId = request.getId();
            int requestId = request.Id;

            try
            {
                ITimeout timeout = TimerHolder.Timer.NewTimeout(new TimerTaskAnonymousInnerClass(this, conn, future, requestId), TimeSpan.FromMilliseconds(timeoutMillis));
                future.addTimeout(timeout);
                var writeFlushTask = conn.Channel.WriteAndFlushAsync(request);
                writeFlushTask.ContinueWith((task) =>
                {
                    if (!task.IsCompletedSuccessfully)
                    {
                        InvokeFuture f = conn.removeInvokeFuture(requestId);
                        if (f != null)
                        {
                            f.cancelTimeout();
                            f.putResponse(commandFactory.createSendFailedResponse(conn.RemoteAddress, task.Exception));
                            f.tryAsyncExecuteInvokeCallbackAbnormally();
                        }
                        logger.LogError("Invoke send failed. The address is {}", ((IPEndPoint)conn.Channel.RemoteAddress).ToString(), task.Exception);
                    }
                });
            }
            catch (Exception e)
            {
                InvokeFuture f = conn.removeInvokeFuture(requestId);
                if (f != null)
                {
                    f.cancelTimeout();
                    f.putResponse(commandFactory.createSendFailedResponse(conn.RemoteAddress, e));
                    f.tryAsyncExecuteInvokeCallbackAbnormally();
                }
                logger.LogError("Exception caught when sending invocation. The address is {}", ((IPEndPoint)conn.Channel.RemoteAddress).ToString(), e);
            }
        }
        public void TestNewTimeoutShouldStopThrowingRejectedExecutionExceptionWhenExistingTimeoutIsCancelled()

        {
            int tickDurationMs = 100;
            var timer          = new HashedWheelTimer(TimeSpan.FromMilliseconds(tickDurationMs), 32, 2);

            timer.NewTimeout(CreateNoOpTimerTask(), TimeSpan.FromSeconds(5));
            ITimeout timeoutToCancel = timer.NewTimeout(CreateNoOpTimerTask(), TimeSpan.FromSeconds(5));

            Assert.True(timeoutToCancel.Cancel());

            Thread.Sleep(tickDurationMs * 5);

            var secondLatch = new CountdownEvent(1);

            timer.NewTimeout(CreateCountdownEventTimerTask(secondLatch), TimeSpan.FromMilliseconds(90));

            secondLatch.Wait();
            timer.StopAsync().Wait();
        }
Пример #18
0
        private void CancelRequestTimeouts(Request request)
        {
            ITimeout sendTimeout = request.SendTimeout;

            if (sendTimeout != null && !sendTimeout.Canceled)
            {
                sendTimeout.Cancel();
            }

            ITimeout receiveTimeout = request.ReceiveTimeout;

            if (receiveTimeout != null && !receiveTimeout.Canceled)
            {
                receiveTimeout.Cancel();
            }

            ITimeout readTimeout = request.ReadTimeout;

            if (readTimeout != null && !readTimeout.Canceled)
            {
                readTimeout.Cancel();
            }
        }
Пример #19
0
 public ConfirmationTimeoutChecker(ITimeout timeoutCheck)
 {
     _timeoutCheck = timeoutCheck ?? throw new ArgumentNullException(nameof(timeoutCheck),
                                                                     "ConfirmationTimeoutChecker - ConfirmationTimeoutChecker: passed NULL instead of proper timeout checking object");
     _checkinterval = CalcCheckInterval(_timeoutCheck.TimeoutValue);
 }
Пример #20
0
 public Task RunAsync(ITimeout timeout)
 {
     timeout.Timer.NewTimeout(this, TimeSpan.FromMilliseconds(100));
     _action();
     return(Task.CompletedTask);
 }
Пример #21
0
        private bool _currentSeq  = false; // Alternate between 0 and 1

        public Transport(string device, int maxSize)
        {
            this.MaxSize = maxSize;
            this.Slip    = new SLIP(device);
            this.Timeout = new Timeout();
        }
Пример #22
0
 public Task RunAsync(ITimeout timeout)
 {
     _action();
     return(Task.CompletedTask);
 }
Пример #23
0
 public Task RunAsync(ITimeout timeout)
 {
     // Console.WriteLine($"IntervalTimerTask is fired at {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss}");
     timeout.Timer.NewTimeout(this, TimeSpan.FromSeconds(5));
     return(Task.FromResult(0));
 }
Пример #24
0
 public Task RunAsync(ITimeout timeout)
 {
     Console.WriteLine($"{_userData} is fired at {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss}");
     return(Task.FromResult(0));
 }
Пример #25
0
 public void Run(ITimeout timeout)
 {
     _imessageExecutor.execute(this);
 }
Пример #26
0
 /// <summary>
 /// Ensures that timeout object initialized
 /// </summary>
 private void EnsureTimeout()
 {
     if (_timeout == null)
     {
         _timeout = StandaloneBootstrapper.Factory.CreateTimeout();
     }
 }
Пример #27
0
 public void Run(ITimeout timeout)
 {
     _func(timeout);
 }
Пример #28
0
 public Task RunAsync(ITimeout timeout)
 {
     _event.Set();
     return(Task.CompletedTask);
 }
Пример #29
0
 public async Task RunAsync(ITimeout timeout)
 {
     await _pool.ReturnAsync(_proxy, HttpStatusCode.OK);
 }
Пример #30
0
 /// <seealso cref= InvokeFuture#addTimeout(io.netty.util.Timeout) </seealso>
 public virtual void addTimeout(ITimeout timeout)
 {
     this.timeout = timeout;
 }
Пример #31
0
 public Task RunAsync(ITimeout timeout)
 {
     _requestedQueue.Timeout(_hash);
     return(Task.CompletedTask);
 }
Пример #32
0
 public CompletitionTimeoutChecker(ICommandIngester ingesterToWorkWith, ITimeout completitionTimeoutChecker)
 {
     _ingesterToWorkWith         = ingesterToWorkWith ?? throw new ArgumentNullException(nameof(ingesterToWorkWith));
     _completitionTimeoutChecker = completitionTimeoutChecker ?? throw new ArgumentNullException(nameof(completitionTimeoutChecker));
     _workingSet = _ingesterToWorkWith.GetIncompletedMessages();
 }