public PerformTimerActionCommand(Timer timer, TimerAction action) { timer.ThrowIfNull("timer"); _timer = timer; _action = action; }
static public void AtInterval(this int ms, TimerAction e) { new Timer( t => { e(t); } ).StartInterval(ms); }
public void Cancel() { int executionCount = 0; Action action = () => executionCount++; var timer = new TimerAction(StubFiber.StartNew(), action, TimeSpan.FromMilliseconds(2)); Thread.Sleep(100); Assert.AreEqual(1, executionCount); timer.Dispose(); Thread.Sleep(150); Assert.AreEqual(1, executionCount); }
public EventTimer(int timerInterval, TimerAction timerAction) { if (timerInterval < 0 || timerInterval > (int.MaxValue / 1000)) { throw new ArgumentOutOfRangeException( string.Format( "The interwal must be between 0 and {0}!!!", int.MaxValue / 1000)); } this.timerInterval = timerInterval; }
public void CallbackFromTimerWithCancel() { var mocks = new MockRepository(); var action = mocks.CreateMock <Action>(); var timer = new TimerAction(action, 2, Timeout.Infinite); var registry = mocks.CreateMock <ISchedulerRegistry>(); registry.Remove(timer); registry.Enqueue(timer.ExecuteOnFiberThread); mocks.ReplayAll(); timer.ExecuteOnTimerThread(registry); }
public void Cancel() { var executionCount = 0; Action action = () => executionCount++; var timer = new TimerAction(action, 1, 2); timer.ExecuteOnFiberThread(); Assert.AreEqual(1, executionCount); timer.Dispose(); timer.ExecuteOnFiberThread(); Assert.AreEqual(1, executionCount); }
public void CallbackFromIntervalTimerWithCancel() { var mocks = new MockRepository(); var action = mocks.CreateMock <Action>(); var timer = new TimerAction(action, 2, 3); var registry = mocks.CreateMock <ISchedulerRegistry>(); registry.Remove(timer); mocks.ReplayAll(); timer.Dispose(); timer.ExecuteOnTimerThread(registry); }
private void Start() { owner = GetComponent <Character>(); this.StaggerHealth = maxStaggerHealth; staggerRecover = new TimerAction(this, this.staggerRecoverDelay, () => { this.StaggerHealth = 100; owner.RemoveStatus(Character.Status.Staggered); }); staggerInvincibilityStop = new TimerAction(this, this.staggerInvincibilityTime, () => { owner.RemoveStatus(Character.Status.Unstoppable); }); }
public void AddAction(TimerAction action) { if (action == null) { return; } if (m_list.Count == 0) { m_timer.Start(); } m_list.Add(action); }
public void Cancel() { int executionCount = 0; void Action() => executionCount++; var timer = new TimerAction(StubFiber.StartNew(), Action, TimeSpan.FromMilliseconds(2)); Thread.Sleep(100); Assert.AreEqual(1, executionCount); timer.Dispose(); Thread.Sleep(150); Assert.AreEqual(1, executionCount); }
private IEnumerator Start() { yield return(null); owner = GetComponentInParent <Character>(); UIElementCanvas.enabled = false; disableUITimer = new TimerAction(this, 5f, () => { UIElementCanvas.enabled = false; }); this.Observe(Message.Combat_LockOnTarget); this.Observe(Message.Combat_HealthChange); }
public static void Main() { TimerAction testDelegate = new TimerAction(PrintSmtDeleg); Timer delegateTimer = new Timer(10, 100, testDelegate); delegateTimer.Run(); Console.WriteLine(); EventTimer evTimer = new EventTimer(10, 100); evTimer.NextEvent += PrintSmt; evTimer.RunTimer(); }
private void TimerCheck() { for (int i = 0; i < timerTableIdList.Count; i++) { TimerAction timer = ((TimerAction)timerTable[timerTableIdList[i]]); if (!timer.deactive) { if (Time.time - timer.startTime >= timer.time) { timer.function(); timer.deactive = true; } } } }
void SetTimeValue(NumberBox sender) { TimerAction timer = (TimerAction)sender.Tag; float time = sender.GetFloat(); if (!sender.Success) { sender.Text = "1"; time = 1; } timer.DefaultTime = (float)Math.Round(time, 1); sender.Text = "" + timer.DefaultTime; }
// Use this for initialization void Start() { if (!owner) { owner = GetComponentInParent <Character>(); } damageText = GetComponent <Text>(); damageText.enabled = false; accumulatedDamage = 0f; this.Observe(Message.Combat_HealthChange); textDisappear = new TimerAction(this, 2f, () => { damageText.enabled = false; accumulatedDamage = 0f; }); }
void ws_LoginCompleted(object sender, LiveSupport.OperatorConsole.LiveChatWS.LoginCompletedEventArgs e) { if (e.Error == null) { currentOperator = (Operator)Common.Convert(e.Result); if (currentOperator != null) { LiveSupport.OperatorConsole.LiveChatWS.AuthenticationHeader h = new LiveSupport.OperatorConsole.LiveChatWS.AuthenticationHeader(); h.OperatorId = currentOperator.OperatorId; h.OperatorSession = currentOperator.OperatorSession; ws.AuthenticationHeaderValue = h; socketHandler = new SocketHandler(); if (Properties.Settings.Default.OperatorConsole_LiveChatWS_Operator.ToLower().Contains("localhost")) { socket = socketHandler.Connect("127.0.0.1"); } else { IPHostEntry entry = Dns.GetHostEntry("lcs.zxkefu.cn"); socket = socketHandler.Connect(entry.AddressList[0].ToString()); } socketHandler.DataArrive += new EventHandler <DataArriveEventArgs>(socketHandler_DataArrive); socketHandler.Exception += new EventHandler <ExceptionEventArgs>(socketHandler_Exception); socketHandler.SendPacket(socket, new LoginAction(currentOperator.OperatorId)); fireConnectStateChange(ConnectionState.Connected, "登录成功"); timerAction = TimerAction.HeartBeat; timer.Enabled = true; ws.GetSystemAdvertiseAsync(productVersion, Guid.NewGuid()); ws.GetLeaveWordAsync(Guid.NewGuid()); ws.GetAllVisitorsAsync(currentOperator.AccountId, Guid.NewGuid()); ws.GetAllOperatorsAsync(Guid.NewGuid()); ws.GetAccountDomainsAsync(Guid.NewGuid()); //Disable the timer checkNewChangesTimer.Enabled = true; } else { fireConnectStateChange(ConnectionState.Disconnected, "登录失败,登录信息输入错误"); } } else { fireConnectStateChange(ConnectionState.Disconnected, "登录失败," + e.Error.Message); } }
public static void RegisterAction(int interval, Action action) { if (_actions.Any(x => x.Action == action)) { return; } var item = new TimerAction(); item.Interval = interval; item.Action = action; item.LastTime = Time(); _actions.Add(item); action(); }
protected override void OnProcess(Action.IAction action) { TimerAction timerAction = action as TimerAction; if (timerAction == null) { return; } LoggerManager.Debug(action.AutomationActionData); if (endDate == DateTime.MinValue) { endDate = DateTime.Now.AddSeconds(timerAction.Seconds); } }
public void CallbackFromIntervalTimerWithCancel() { int executionCount = 0; Action action = () => executionCount++; using (IFiber stubFiber = StubFiber.StartNew()) { var timer = new TimerAction(stubFiber, action, TimeSpan.FromMilliseconds(2), TimeSpan.FromMilliseconds(150)); Thread.Sleep(100); Assert.AreEqual(1, executionCount); timer.Dispose(); Thread.Sleep(150); Assert.AreEqual(1, executionCount); } }
public frm_Main() { InitializeComponent(); dtp_DateRestore.CustomFormat = "dd-MM-yyyy"; dtp_TimeRestore.CustomFormat = "HH:mm:ss"; Thread thread = new Thread(new ThreadStart(() => { TimerAction.AddTimer((args, e) => { InvokeUI(() => { this.lbl_Time.Text = DateTime.Now.ToLongTimeString(); }); }, 1000); })); thread.Start(); uc_login.ResponseResultLogin += Uc_login_ResponseResultLogin; uc_login.BringToFront(); }
public async Task DoActionOnTimer(string userId, string timerId, TimerAction action) { var currentTimer = await timerRepository.GetTimerAsync(timerId).ConfigureAwait(false); currentTimer = currentTimer ?? throw new ArgumentException($"Timer with {timerId} was not found!"); ValidateUserHasAccessToTimer(userId, currentTimer); switch (action) { case TimerAction.Start: await RunTimerAsync(currentTimer).ConfigureAwait(false); break; case TimerAction.Repeat: await RerunTimerAsync(currentTimer).ConfigureAwait(false); break; case TimerAction.Stop: await StopTimerAsync(currentTimer).ConfigureAwait(false); break; case TimerAction.Pause: await PauseTimerAsync(currentTimer).ConfigureAwait(false); break; case TimerAction.Expire: await ExpireTimerAsync(currentTimer).ConfigureAwait(false); break; case TimerAction.Delete: await DeleteTimerAsync(currentTimer).ConfigureAwait(false); break; default: throw new ArgumentException("Handler for the given action was not found"); } }
static void Main() { TimerAction act1 = new TimerAction(PrintEvery3Secs); Timer firstTimer = new Timer(3, act1); Thread firstThread = new Thread(new ThreadStart(firstTimer.Tick)); firstThread.Start(); TimerAction act2 = new TimerAction(PrintEverySecond); Timer secondTimer = new Timer(1, act2); Thread secondThread = new Thread(new ThreadStart(secondTimer.Tick)); secondThread.Start(); TimerAction act3 = new TimerAction(delegate() { Console.WriteLine("Honestly, I have no idea what I'm doing :)"); }); Timer thirdTimer = new Timer(2, act3); Thread thirdThread = new Thread(new ThreadStart(thirdTimer.Tick)); thirdThread.Start(); }
private void DoTimerAction(TimerAction timerAction) { switch (timerAction) { case TimerAction.None: //Do nothing break; case TimerAction.Start: StartTimer(); break; case TimerAction.Stop: StopTimer(); break; case TimerAction.Reset: ResetTimer(); break; } }
//SetTimer : 지정한 시간 이후 TimerAction 으로 지정한 작업을 수행한다. //Destory : 이 오브젝트를 파괴한다. //Stop : 오브젝트에 설정된 모든 동작들을 중지 또는 삭제 한다. AttackObject의 경우 충돌 이벤트도 포함된다. // 주의 : 동작에 의해 이미 일어난 변화를 초기화 시키지 않음 public void SetTimer(float seconds, TimerAction action) { if (seconds < 0f) { throw new System.ArgumentOutOfRangeException(nameof(seconds), "Must be greater than or equal to 0."); } Method timerMethod = null; switch (action) { case TimerAction.Destory: timerMethod = DestoryThis; break; case TimerAction.Stop: timerMethod = StopActions; break; } StartCoroutine(Timer(seconds, timerMethod)); }
//Responsible for adding the timers without repeating Key public static void AntiExistente(TimerAction callback) { try { timerSync = UnityEngine.Time.realtimeSinceStartup + callback.time; if (listTimers.ContainsKey(timerSync)) { callback.time += 0.05001f; AntiExistente(callback); } else { //debug UnityEngine.Debug.Log("timer current: " + UnityEngine.Time.realtimeSinceStartup.ToString() + " timer event: " + timerSync.ToString()); listTimers.Add(timerSync, callback); } } catch (Exception ex) { Logger.LogDebug("[TimerEvento] Error AntiExistente! " + ex); } }
public void CallbackFromIntervalTimerWithCancel() { int executionCount = 0; void Action() { executionCount++; } using (StubFiber stubFiber = new StubFiber()) { TimerAction timer = new TimerAction(stubFiber, Action, TimeSpan.FromMilliseconds(2), TimeSpan.FromMilliseconds(150)); Thread.Sleep(100); Assert.AreEqual(1, executionCount); timer.Dispose(); Thread.Sleep(150); Assert.AreEqual(1, executionCount); } }
private UnityEvent SelectEvent(TimerAction action) { switch (action) { case TimerAction.Start: { return(OnTimerStartEvent); } case TimerAction.CountDown: { return(OnTimerCountDownEvent); } case TimerAction.Tick: { return(OnTimerTickEvent); } default: { Debug.LogError("Wrong Timer Action Expression"); return(null); } } }
public IEnumerator ActionAfterTimer(TimerAction action) { while (true) { if (TimeIsOver()) { if (pauseActive) { yield return(null); } else { action(); yield break; } } else { yield return(null); } } }
private void InitStateMachine() { blackboard = new StateBlackboard(); blackboard.Add <bool>(BlackboardKey.DamageFlag, false); blackboard.Add <bool>(BlackboardKey.RepeatDamageFlag, false); blackboard.Add <Transform>(BlackboardKey.Transform, transform); blackboard.Add <float>(BlackboardKey.RunRange, 3f); EnemyIdleState idleState = EnemyIdleState.Create(blackboard, animator, "Idle", 0); StateNode idleNode = new StateNode(idleState, new Condition(() => { return(true); })); SetAnimTriggerAction idleAction = new SetAnimTriggerAction(blackboard, animator, "Idle"); SetAnimTriggerAction runAction = new SetAnimTriggerAction(blackboard, animator, "Run"); TimerAction timerAction = new TimerAction(blackboard, 0.5f, 1.5f); SetRandomDestinationAction destinationAction = new SetRandomDestinationAction(blackboard, transform.position, 6f); MoveToDestinationAction moveToAction = new MoveToDestinationAction(blackboard, navAgent); SetSkillAction setSkillAction = new SetSkillAction(blackboard, skillController); LookAtTargetAction lookAtAction = new LookAtTargetAction(blackboard, transform); SetAnimTriggerAction attackAction = new SetAnimTriggerAction(blackboard, animator, BlackboardKey.AnimTrigger, true); RangedAttackState attackState = new RangedAttackState(blackboard, idleAction, timerAction, destinationAction, runAction, moveToAction, setSkillAction, lookAtAction, attackAction, 300); StateNode attackNode = new StateNode(attackState, new Condition(() => target != null)); DamageState damageState = DamageState.Create(blackboard, animator, "Damage", 500); StateNode damageNode = new StateNode(damageState, new Condition(() => { return(blackboard.Get <bool>(BlackboardKey.DamageFlag)); })); DeathState deathState = DeathState.Create(blackboard, animator, "Death", int.MaxValue); StateNode deathNode = new StateNode(deathState, new Condition(() => { return(!self.IsAlive); })); List <StateNode> nodes = new List <StateNode>(); nodes.Add(idleNode); nodes.Add(attackNode); nodes.Add(damageNode); nodes.Add(deathNode); stateMachine = new StateMachine(blackboard, nodes, idleState); }
void socketHandler_Exception(object sender, ExceptionEventArgs e) { if (e.Exception is SocketException && !socket.Connected) { if (autoLoginEnabled) { timerAction = TimerAction.ReConnect; timer.Start(); } fireConnectStateChange(ConnectionState.Disconnected, e.Exception.Message); } }
void ws_LoginCompleted(object sender, LiveSupport.OperatorConsole.LiveChatWS.LoginCompletedEventArgs e) { if (e.Error == null) { currentOperator = (Operator)Common.Convert(e.Result); if (currentOperator != null) { LiveSupport.OperatorConsole.LiveChatWS.AuthenticationHeader h = new LiveSupport.OperatorConsole.LiveChatWS.AuthenticationHeader(); h.OperatorId = currentOperator.OperatorId; h.OperatorSession = currentOperator.OperatorSession; ws.AuthenticationHeaderValue = h; socketHandler = new SocketHandler(); if (Properties.Settings.Default.OperatorConsole_LiveChatWS_Operator.ToLower().Contains("localhost")) { socket = socketHandler.Connect("127.0.0.1"); } else { IPHostEntry entry = Dns.GetHostEntry("lcs.zxkefu.cn"); socket = socketHandler.Connect(entry.AddressList[0].ToString()); } socketHandler.DataArrive += new EventHandler<DataArriveEventArgs>(socketHandler_DataArrive); socketHandler.Exception += new EventHandler<ExceptionEventArgs>(socketHandler_Exception); socketHandler.SendPacket(socket, new LoginAction(currentOperator.OperatorId)); fireConnectStateChange(ConnectionState.Connected, "登录成功"); timerAction = TimerAction.HeartBeat; timer.Enabled = true; ws.GetSystemAdvertiseAsync(productVersion, Guid.NewGuid()); ws.GetLeaveWordAsync(Guid.NewGuid()); ws.GetAllVisitorsAsync(currentOperator.AccountId, Guid.NewGuid()); ws.GetAllOperatorsAsync(Guid.NewGuid()); ws.GetAccountDomainsAsync(Guid.NewGuid()); //Disable the timer checkNewChangesTimer.Enabled = true; } else { fireConnectStateChange(ConnectionState.Disconnected, "登录失败,登录信息输入错误"); } } else { fireConnectStateChange(ConnectionState.Disconnected, "登录失败," + e.Error.Message); } }
public UpdateRateCounter() { _timer = new TimerAction { Action = Accumulate, Interval = TimeSpan.FromMilliseconds(500) }; }
private static extern int navigator_invoke_timer_registration_set_action(IntPtr reg, TimerAction action);
public void EventLoop() { _running = true; while (_running) { object action; while (_pendingAdd.TryTake(out action)) { if (action is TimerAction) { //is timer _sleepingMs.Add((TimerAction)action); } else { object[] keyAndAction = (object[])(action); Socket socket = (Socket)keyAndAction[0]; if (!_socketActions.ContainsKey(socket)) { _socketActions.Add(socket, (SocketAction)keyAndAction[1]); _sockets.Add(socket); } } } _sleepingMs.Sort((lhs, rhs) => { int l = (int)(lhs.Wait); int r = (int)(rhs.Wait); return(l == r ? 0 : (l < r ? 1 : -1)); }); int removed = 0; foreach (var a in _sleepingMs) { if (a.Wait == 0) { a.Action(a.Param); ++removed; } else { break; } } _sleepingMs.RemoveRange(0, removed); Socket toRemove; bool hasRemove = _pendingRemove.TryTake(out toRemove); if (hasRemove) { _socketActions.Remove(toRemove); _sockets.Remove(toRemove); } var check = new List <Socket> [3]; for (int i = 0; i < check.Length; ++i) { check[i] = new List <Socket>(_sockets); } TimerAction waitAndAction = null; if (_sleepingMs.Count > 0) { waitAndAction = _sleepingMs[0]; _sleepingMs.RemoveAt(0); } int sleep = (waitAndAction == null ? IDLE_MS : Math.Min(IDLE_MS, waitAndAction.Wait)); Socket.Select(check[0], check[1], check[2], sleep); for (int i = 0; i < check.Length; ++i) { foreach (var socket in check[i]) { var inv = _socketActions[socket].RWE[i]; if (inv != null) { inv.Invoke(); } } } if (waitAndAction != null) { waitAndAction.Action.Invoke(waitAndAction.Param); } removed = 0; foreach (var a in _sleepingMs) { a.Wait -= sleep; if (a.Wait <= 0) { a.Action.Invoke(a.Param); ++removed; } else { break; } } _sleepingMs.RemoveRange(0, removed); } }
private static void Add(TimerAction action) { actions.Add(action); }
private static TimerAction CreateAction(double time, Action handler,Action<int> progresshandler) { TimerAction action = new TimerAction(); action.Time = time; action.Handler = handler; action.Notifer = progresshandler; return action; }
private static XmlDocument FillIntervalCompletedTemplate(string intervalType, string imageSrc, TimerAction action) { return(ToXmlDocument(Properties.Resources.toast_template_interval_completed .Replace("{interval_type}", intervalType) .Replace("{image_src}", imageSrc) .Replace("{action_content}", action.Content) .Replace("{action_args}", action.Args))); }
public static PerformTimerActionCommand PerformTimerAction(Timer timer, TimerAction action) { return new PerformTimerActionCommand(timer, action); }
public Looters(LootContainer lootContainer) { _lootContainer = lootContainer; _action = new TimerAction(CleanUpLooters, TimeSpan.FromSeconds(1000)); }