protected override void Execute(IJobExecutionContext context)
            {
                try
                {
                    var runId = (string)context.MergedJobDataMap[RunIdKey];


                    var workflowRun = Entity.Get <WorkflowRun>(long.Parse(runId));

                    if (workflowRun != null && workflowRun.WorkflowRunStatus_Enum == WorkflowRunState_Enumeration.WorkflowRunPaused)
                    {
                        var workflowEvent = new TimeoutEvent();
                        WorkflowRunner.Instance.ResumeWorkflow(workflowRun, workflowEvent);
                    }
                    else
                    {
                        // Ignore sequence numbers that no longer exist. It's probably a stale timeout.
                        EventLog.Application.WriteTrace("Timeout event: Ignoring invalid or stale paused workflow run: {0}", runId);
                    }
                }
                catch (Exception ex)
                {
                    throw new JobExecutionException("Failed to execute timeout.", ex);
                }
            }
Esempio n. 2
0
 public object Clear()
 {
     Prev = null;
     Next = null;
     Interlocked.Exchange(ref _action, null);
     return(Interlocked.Exchange(ref _state, null));
 }
Esempio n. 3
0
        private void OnTimeout()
        {
            this.Exception = new TimeoutException();
            TimeoutEvent evt = new TimeoutEvent(session, msgId, coroutine);

            Session.EventLoop.EnqueuEvent(evt);
        }
Esempio n. 4
0
 public void ScheduleTimeout(IResumableActivity activityInstance, WorkflowRun workflowRun, decimal timeoutMinutes)
 {
     timeoutAction = () =>
     {
         var workflowEvent = new TimeoutEvent();
         WorkflowRunner.Instance.ResumeWorkflow(workflowRun, workflowEvent);
     };
 }
Esempio n. 5
0
        private static void SetTimer(ref mdr.CallFrame callFrame, bool isInterval)
        {
            mdr.DFunction handler = null;
            //TODO: We might need to do it better using sth like Callable property
            if (callFrame.Arg0.ValueType == mdr.ValueTypes.Function)
            {
                handler = callFrame.Arg0.AsDFunction();
            }
            else if (callFrame.Arg0.ValueType == mdr.ValueTypes.String)
            {
                handler = HTMLRuntime.Instance.PrepareScript(callFrame.Arg0.AsString());
            }
            else
            {
                Debug.WriteLine("Invalid argument type {0} for setInterval", callFrame.Arg0.ValueType);
                //Trace.Fail("Invalid argument type {0} for setInterval", callFrame.Arg0.ValueType);
            }
            //TODO: Consider the case in which it's nor function or string

            long         times    = (long)callFrame.Arg1.AsInt32();
            int          argCount = callFrame.PassedArgsCount;
            TimeoutEvent timeout  = new TimeoutEvent(times, isInterval);

            timeout.CallFrame.Function = handler;

            Debug.WriteLineIf(
                handler == null
                , "The {0} handler function of timer {1} is null and arg0.ValueType={2} with value {3}"
                , (isInterval ? "setInterval" : "setTimeout")
                , timeout.Id
                , callFrame.Arg0.ValueType
                , mjr.Operations.Convert.ToString.Run(ref callFrame.Arg0)
                );
            //TODO: we need the following ASSERT, but for some reason, this will cause strange problems with WrappedObject.cpp:85 gcGetWrapper(), so we're going to catch this again later in TimerQueue.ProcessEvents
            //Debug.Assert(timeout.CallFrame.Function != null, "The setTimeout handler function must not be null");

            if (argCount > 2)
            {
                timeout.CallFrame.PassedArgsCount = argCount - 2;
                if (timeout.CallFrame.PassedArgsCount > 4)
                {
                    timeout.CallFrame.Arguments = new mdr.DValue[timeout.CallFrame.PassedArgsCount - 4];
                }
                for (int i = 0; i < argCount - 2; i++)
                {
                    var arg = callFrame.Arg(i + 2);
                    timeout.CallFrame.SetArg(i, ref arg);
                }
            }
            HTMLRuntime.Instance.TimerQueue.SetTimeoutOrInterval(timeout);
            callFrame.Return.Set(timeout.Id);
        }
Esempio n. 6
0
        private static void SetTimer(ref mdr.CallFrame callFrame, bool isInterval)
        {
          mdr.DFunction handler = null;
          //TODO: We might need to do it better using sth like Callable property
          if (callFrame.Arg0.ValueType == mdr.ValueTypes.Function)
          {
            handler = callFrame.Arg0.AsDFunction();
          }
          else if (callFrame.Arg0.ValueType == mdr.ValueTypes.String)
          {
            handler = HTMLRuntime.Instance.PrepareScript(callFrame.Arg0.AsString());
          }
          else
          {
            Debug.WriteLine("Invalid argument type {0} for setInterval", callFrame.Arg0.ValueType);
            //Trace.Fail("Invalid argument type {0} for setInterval", callFrame.Arg0.ValueType);
          }
          //TODO: Consider the case in which it's nor function or string

          long times = (long)callFrame.Arg1.AsInt32();
          int argCount = callFrame.PassedArgsCount;
          TimeoutEvent timeout = new TimeoutEvent(times, isInterval);
          timeout.CallFrame.Function = handler;

          Debug.WriteLineIf(
            handler == null
            , "The {0} handler function of timer {1} is null and arg0.ValueType={2} with value {3}"
            , (isInterval ? "setInterval" : "setTimeout")
            , timeout.Id
            , callFrame.Arg0.ValueType
            , mjr.Operations.Convert.ToString.Run(ref callFrame.Arg0)
          );
          //TODO: we need the following ASSERT, but for some reason, this will cause strange problems with WrappedObject.cpp:85 gcGetWrapper(), so we're going to catch this again later in TimerQueue.ProcessEvents
          //Debug.Assert(timeout.CallFrame.Function != null, "The setTimeout handler function must not be null");
          
          if (argCount > 2)
          {
            timeout.CallFrame.PassedArgsCount = argCount - 2;
            if (timeout.CallFrame.PassedArgsCount > 4)
            {
              timeout.CallFrame.Arguments = new mdr.DValue[timeout.CallFrame.PassedArgsCount - 4];
            }
            for (int i = 0; i < argCount - 2; i++)
            {
              var arg = callFrame.Arg(i + 2);
              timeout.CallFrame.SetArg(i, ref arg);
            }
          }
          HTMLRuntime.Instance.TimerQueue.SetTimeoutOrInterval(timeout);
          callFrame.Return.Set(timeout.Id);
        }
Esempio n. 7
0
 private void Update()
 {
     if (Time.time - startTime > time && time > 0)
     {
         if (TimeoutEvent != null)
         {
             TimeoutEvent.Invoke(this, parentWeapon);
         }
         Destroy(this.gameObject, 0.4f);
         if (DestroyEvent != null)
         {
             DestroyEvent.Invoke(this);
         }
     }
 }
Esempio n. 8
0
    // Update is called once per frame
    void Update()
    {
        if (stopTimer == false)
        {
            time -= Time.deltaTime;
        }

        time = Mathf.Max(time, 0f);

        timerText.text = time.ToString("f1");

        if (time <= 0f & timeOut == false)
        {
            TimeoutEvent?.Invoke();
            timeOut = true;
        }
    }
Esempio n. 9
0
        public void SetTimeout(int msgID, int timeout)
        {
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval  = timeout * 1000;
            timer.AutoReset = false;
            timer.Elapsed  += delegate
            {
                TimeoutEvent evt = new TimeoutEvent(session);
                evt.msgID = msgID;
                session.eventQueue.Enqueue(evt);
            };
            timer.Start();

            if (false == timers.ContainsKey(msgID))
            {
                timers.Add(msgID, new List <System.Timers.Timer>());
            }
            timers[msgID].Add(timer);
        }
Esempio n. 10
0
        /// <summary>
        /// Callback method for when the client receives a login response from a server connection.
        /// </summary>
        /// <param name="loginResponse">The LoginResponse packet data.</param>
        private void OnConnect(LoginResponse loginResponse)
        {
            Logger.Get().Info(this, "Connection to server success");

            // De-register the connect failed and register the actual timeout handler if we time out
            UpdateManager.OnTimeout -= OnConnectTimedOut;
            UpdateManager.OnTimeout += () => {
                ThreadUtil.RunActionOnMainThread(() => {
                    TimeoutEvent?.Invoke();
                });
            };

            // Invoke callback if it exists on the main thread of Unity
            ThreadUtil.RunActionOnMainThread(() => {
                ConnectEvent?.Invoke(loginResponse);
            });

            IsConnected = true;
        }
Esempio n. 11
0
            private void ListenToMaintenanceWorker()
            {
                var firstIteration           = true;
                var onErrorDelayTime         = _parent.Config.OnErrorDelayTime.AsTimeSpan;
                var receiveFromWorkerTimeout = _parent.Config.ReceiveFromWorkerTimeout.AsTimeSpan;
                var tcpTimeout = _parent.Config.TcpConnectionTimeout.AsTimeSpan;

                if (tcpTimeout < receiveFromWorkerTimeout)
                {
                    if (_log.IsInfoEnabled)
                    {
                        _log.Info(
                            $"Warning: TCP timeout is lower than the receive from worker timeout ({tcpTimeout} < {receiveFromWorkerTimeout}), " +
                            "this could affect the cluster observer's decisions.");
                    }
                }

                while (_token.IsCancellationRequested == false)
                {
                    try
                    {
                        if (firstIteration == false)
                        {
                            // avoid tight loop if there was timeout / error
                            _token.WaitHandle.WaitOne(onErrorDelayTime);
                            if (_token.IsCancellationRequested)
                            {
                                return;
                            }
                        }
                        firstIteration = false;

                        TcpConnectionInfo tcpConnection = null;
                        using (var timeout = new CancellationTokenSource(tcpTimeout))
                            using (var combined = CancellationTokenSource.CreateLinkedTokenSource(_token, timeout.Token))
                            {
                                tcpConnection = ReplicationUtils.GetTcpInfo(Url, null, "Supervisor", _parent._server.Server.Certificate.Certificate, combined.Token);
                                if (tcpConnection == null)
                                {
                                    continue;
                                }
                            }

                        var connection = ConnectToClientNode(tcpConnection, _parent._server.Engine.TcpConnectionTimeout);
                        var tcpClient  = connection.TcpClient;
                        var stream     = connection.Stream;
                        using (tcpClient)
                            using (_cts.Token.Register(tcpClient.Dispose))
                                using (_contextPool.AllocateOperationContext(out JsonOperationContext contextForParsing))
                                    using (_contextPool.AllocateOperationContext(out JsonOperationContext contextForBuffer))
                                        using (contextForBuffer.GetMemoryBuffer(out var readBuffer))
                                            using (var timeoutEvent = new TimeoutEvent(receiveFromWorkerTimeout, $"Timeout event for: {_name}", singleShot: false))
                                            {
                                                timeoutEvent.Start(OnTimeout);
                                                var unchangedReports = new List <DatabaseStatusReport>();

                                                while (_token.IsCancellationRequested == false)
                                                {
                                                    contextForParsing.Reset();
                                                    contextForParsing.Renew();
                                                    BlittableJsonReaderObject rawReport;
                                                    try
                                                    {
                                                        // even if there is a timeout event, we will keep waiting on the same connection until the TCP timeout occurs.

                                                        rawReport = contextForParsing.Sync.ParseToMemory(stream, _readStatusUpdateDebugString, BlittableJsonDocumentBuilder.UsageMode.None, readBuffer);
                                                        timeoutEvent.Defer(_parent._leaderClusterTag);
                                                    }
                                                    catch (Exception e)
                                                    {
                                                        if (_token.IsCancellationRequested)
                                                        {
                                                            return;
                                                        }

                                                        if (_log.IsInfoEnabled)
                                                        {
                                                            _log.Info("Exception occurred while reading the report from the connection", e);
                                                        }

                                                        ReceivedReport = new ClusterNodeStatusReport(new ServerReport(), new Dictionary <string, DatabaseStatusReport>(),
                                                                                                     ClusterNodeStatusReport.ReportStatus.Error,
                                                                                                     e,
                                                                                                     DateTime.UtcNow,
                                                                                                     _lastSuccessfulReceivedReport);

                                                        break;
                                                    }

                                                    _parent.ForTestingPurposes?.BeforeReportBuildAction(this);

                                                    var nodeReport = BuildReport(rawReport, connection.SupportedFeatures);
                                                    timeoutEvent.Defer(_parent._leaderClusterTag);


                                                    UpdateNodeReportIfNeeded(nodeReport, unchangedReports);
                                                    unchangedReports.Clear();

                                                    ReceivedReport = _lastSuccessfulReceivedReport = nodeReport;
                                                    _parent.ForTestingPurposes?.AfterSettingReportAction(this);
                                                }
                                            }
                    }
                    catch (Exception e)
                    {
                        if (_token.IsCancellationRequested)
                        {
                            return;
                        }

                        if (_log.IsInfoEnabled)
                        {
                            _log.Info($"Exception was thrown while collecting info from {ClusterTag}", e);
                        }

                        ReceivedReport = new ClusterNodeStatusReport(new ServerReport(), new Dictionary <string, DatabaseStatusReport>(),
                                                                     ClusterNodeStatusReport.ReportStatus.Error,
                                                                     e,
                                                                     DateTime.UtcNow,
                                                                     _lastSuccessfulReceivedReport);
                    }
                }
            }
            private void ListenToMaintenanceWorker()
            {
                var needToWait               = false;
                var firstIteration           = true;
                var onErrorDelayTime         = _parent.Config.OnErrorDelayTime.AsTimeSpan;
                var receiveFromWorkerTimeout = _parent.Config.ReceiveFromWorkerTimeout.AsTimeSpan;
                var tcpTimeout               = _parent.Config.TcpConnectionTimeout.AsTimeSpan;

                if (tcpTimeout < receiveFromWorkerTimeout)
                {
                    if (_log.IsInfoEnabled)
                    {
                        _log.Info(
                            $"Warning: TCP timeout is lower than the receive from worker timeout ({tcpTimeout} < {receiveFromWorkerTimeout}), " +
                            "this could affect the cluster observer's decisions.");
                    }
                }

                TcpConnectionInfo tcpConnection = null;

                while (_token.IsCancellationRequested == false)
                {
                    try
                    {
                        if (needToWait)
                        {
                            needToWait = false; // avoid tight loop if there was timeout / error
                            if (firstIteration == false)
                            {
                                _token.WaitHandle.WaitOne(onErrorDelayTime);
                            }
                            firstIteration = false;
                            using (var timeout = new CancellationTokenSource(tcpTimeout))
                                using (var combined = CancellationTokenSource.CreateLinkedTokenSource(_token, timeout.Token))
                                {
                                    tcpConnection = ReplicationUtils.GetTcpInfo(Url, null, "Supervisor", _parent._server.Server.Certificate.Certificate, combined.Token);
                                }
                        }

                        if (tcpConnection == null)
                        {
                            needToWait = true;
                            continue;
                        }

                        var connection = ConnectToClientNode(tcpConnection, _parent._server.Engine.TcpConnectionTimeout);
                        var tcpClient  = connection.TcpClient;
                        var stream     = connection.Stream;
                        using (tcpClient)
                            using (_cts.Token.Register(tcpClient.Dispose))
                                using (_contextPool.AllocateOperationContext(out JsonOperationContext context))
                                    using (var timeoutEvent = new TimeoutEvent(receiveFromWorkerTimeout, $"Timeout event for: {_name}", singleShot: false))
                                    {
                                        timeoutEvent.Start(OnTimeout);
                                        while (_token.IsCancellationRequested == false)
                                        {
                                            BlittableJsonReaderObject rawReport;
                                            try
                                            {
                                                // even if there is a timeout event, we will keep waiting on the same connection until the TCP timeout occurs.
                                                rawReport = context.ReadForMemory(stream, _readStatusUpdateDebugString);
                                                timeoutEvent.Defer(_parent._leaderClusterTag);
                                            }
                                            catch (Exception e)
                                            {
                                                if (_token.IsCancellationRequested)
                                                {
                                                    return;
                                                }

                                                if (_log.IsInfoEnabled)
                                                {
                                                    _log.Info("Exception occurred while reading the report from the connection", e);
                                                }

                                                ReceivedReport = new ClusterNodeStatusReport(new Dictionary <string, DatabaseStatusReport>(),
                                                                                             ClusterNodeStatusReport.ReportStatus.Error,
                                                                                             e,
                                                                                             DateTime.UtcNow,
                                                                                             _lastSuccessfulReceivedReport);

                                                needToWait = true;
                                                break;
                                            }

                                            var report = BuildReport(rawReport);
                                            timeoutEvent.Defer(_parent._leaderClusterTag);

                                            ReceivedReport = _lastSuccessfulReceivedReport = report;
                                        }
                                    }
                    }
                    catch (Exception e)
                    {
                        if (_log.IsInfoEnabled)
                        {
                            _log.Info($"Exception was thrown while collecting info from {ClusterTag}", e);
                        }

                        ReceivedReport = new ClusterNodeStatusReport(new Dictionary <string, DatabaseStatusReport>(),
                                                                     ClusterNodeStatusReport.ReportStatus.Error,
                                                                     e,
                                                                     DateTime.UtcNow,
                                                                     _lastSuccessfulReceivedReport);

                        needToWait = true;
                    }
                }
            }
Esempio n. 13
0
 protected virtual void onTimeoutEvent()
 {
     TimeoutEvent?.Invoke(this, EventArgs.Empty);
 }
Esempio n. 14
0
 public Timeout(int milliseconds, TimeoutEvent onTimeout)
     : this(milliseconds)
 {
     _onTimeout = onTimeout;
 }
Esempio n. 15
0
 public void Visit(TimeoutEvent @event)
 {
     _enumerator.At = _runner.Environment.Now + @event.Delay;
     _runner.Enqueue(_enumerator);
 }
Esempio n. 16
0
        private void SetRoomState(RoomState roomState)
        {
            LogInfoJson(hassEventArgs, data: roomState.ToString());
            var _attributes = SetAttributes(roomState);

            switch (roomState)
            {
            case RoomState.Idle:
                SetRoomStateIdle();
                break;

            case RoomState.Active:
                SetRoomStateActive();
                break;

            case RoomState.Disabled:
                SetRoomStateDisabled();
                break;

            case RoomState.Override:
                SetRoomStateOverride();
                break;

            case RoomState.RandomWait:
                SetRoomStateRandom();
                break;
            }

            void SetTimer(TimeSpan ts, Action action)
            {
                DisposeTimer();
                Timer = _app.RunIn(ts, action);
            }

            void DisposeTimer()
            {
                Timer?.Dispose();
                Timer = null;
            }

            void SetRoomStateRandom()
            {
                var waitDuration = _controller.GetRandomDuration();

                SetRandomOnTimer(waitDuration);
                _attributes = SetAttributes(RoomState.RandomWait, waitDuration);
                _app.SetState(_roomConfig.RoomPresenceEntityId, RoomState.RandomWait.ToString().ToLower(), _attributes);
            }

            void SetRandomOnTimer(int duration)
            {
                SetTimer(TimeSpan.FromMinutes(duration), () =>
                {
                    if (!LuxBelowThreshold())
                    {
                        return;
                    }
                    var onDuration = _controller.GetRandomDuration();

                    TurnOnControlEntities();
                    TurnOffRandomAndReset(onDuration);

                    _attributes = SetAttributes(RoomState.RandomActive, onDuration);
                    _app.SetState(_roomConfig.RoomPresenceEntityId, RoomState.RandomActive.ToString().ToLower(), _attributes);
                });
            }

            void TurnOffRandomAndReset(int duration)
            {
                SetTimer(TimeSpan.FromMinutes(duration), () =>
                {
                    var offDuration = _controller.GetRandomDuration();
                    SetRoomStateIdle();
                    SetRandomOnTimer(offDuration);

                    _attributes = SetAttributes(RoomState.RandomWait, offDuration);
                    _app.SetState(_roomConfig.RoomPresenceEntityId, RoomState.RandomWait.ToString().ToLower(), _attributes);
                });
            }

            void SetRoomStateOverride()
            {
                if (Timer != null && (RoomIs(RoomState.Active) || RoomIs(RoomState.RandomActive)))
                {
                    return;
                }

                SetTimer(_overrideTimeout, () => TimeoutEvent.Invoke(this, new HassEventArgs(_roomConfig.Name, nameof(SetRoomStateOverride))
                {
                    EntityId = _eventEntity
                }));
                _app.SetState(_roomConfig.RoomPresenceEntityId, RoomState.Override.ToString().ToLower(), _attributes);
            }

            void SetRoomStateDisabled()
            {
                DisposeTimer();
                _brightnessTimer?.Dispose();
                _brightnessTimer = null;
                _app.SetState(_roomConfig.RoomPresenceEntityId, RoomState.Disabled.ToString().ToLower(), null);
            }

            void SetRoomStateActive()
            {
                SetTimer(Timeout, () => TimeoutEvent.Invoke(this, new HassEventArgs(_roomConfig.Name, nameof(SetRoomStateActive))
                {
                    EntityId = _eventEntity
                }));
                _app.SetState(_roomConfig.RoomPresenceEntityId, RoomState.Active.ToString().ToLower(), _attributes);
                TurnOnControlEntities();
            }

            void SetRoomStateIdle()
            {
                TurnOffControlEntities();
                _brightnessTimer?.Dispose();
                _brightnessTimer = null;
                DisposeTimer();
                _app.Delay(TimeSpan.FromSeconds(1));
                _app.SetState(_roomConfig.RoomPresenceEntityId, RoomState.Idle.ToString().ToLower(), _attributes);
                EnableCircadian();
            }

            object SetAttributes(RoomState state, int?randomDuration = null)
            {
                string expiryAtt = "";

                if (randomDuration == null)
                {
                    expiryAtt =
                        state == RoomState.Override
                            ? DateTime.Now.AddSeconds(_overrideTimeout.TotalSeconds).ToString("yyyy-MM-dd HH:mm:ss")
                            : Expiry;
                }
                else
                {
                    expiryAtt = DateTime.Now.AddMinutes((int)randomDuration).ToString("yyyy-MM-dd HH:mm:ss");
                }


                var attrs = new
                {
                    EventEntity = _eventEntity,
                    ActiveEntities,
                    PresenceEntityIds = _presenceEntityIds,
                    KeepAliveEntities,
                    ControlEntityIds      = _controlEntityIds,
                    NightControlEntityIds = _nightControlEntityIds,
                    _roomConfig.RandomEntityId,
                    _roomConfig.RandomStates,
                    RandomDuration = randomDuration ?? 0,
                    Expiry         = expiryAtt
                };

                LogVerboseJson(hassEventArgs, data: attrs);
                return(attrs);
            }
        }
Esempio n. 17
0
 public Timeout(int milliseconds, TimeoutEvent onTimeout)
     : this(milliseconds)
 {
     _onTimeout = onTimeout;
 }