private Brush Convert(TimerState state) { Brush result = null; switch (state) { case TimerState.Ready: result = ReadyBrush; break; case TimerState.Sprint: result = SprintBrush; break; case TimerState.HomeStraight: result = HomeStraightBrush; break; case TimerState.Break: result = BreakBrush; break; case TimerState.BreakOverrun: result = BreanOverrunBrush; break; default: break; } return result; }
public void Stop() { State = TimerState.Stopped; CurrentTime = TimeSpan.Zero; OnStopped(); Stopped.Raise(this, EventArgs.Empty); }
private void buttonStart_Click(object sender, EventArgs e) { switch (this.timerState) { case TimerState.Stopped: this.elapsedTime = TimeSpan.FromSeconds(0); this.timer.Start(); this.labelTime.Text = Config.GetTimeString(TimeSpan.FromSeconds(0)); this.buttonStart.Text = @"Pause"; this.timerState = TimerState.Started; this.buttonStop.Enabled = true; break; case TimerState.Started: this.timer.Stop(); this.buttonStart.Text = @"Start"; this.config.Save(); this.timerState = TimerState.Paused; break; case TimerState.Paused: this.timer.Start(); this.buttonStart.Text = @"Pause"; this.timerState = TimerState.Started; break; default: break; } }
public Timer() { if (System.Diagnostics.Debugger.IsAttached) { m_SprintDuration = TimeSpan.FromSeconds(10); m_HomeStraightDuration = TimeSpan.FromSeconds(1); m_BreakDuration = TimeSpan.FromSeconds(5); m_MaxBreakDuration = TimeSpan.FromSeconds(10); } else { m_SprintDuration = TimeSpan.FromMinutes(25); m_HomeStraightDuration = TimeSpan.FromMinutes(1); m_BreakDuration = TimeSpan.FromMinutes(5); m_MaxBreakDuration = TimeSpan.FromMinutes(60); } m_InternalStates = new Dictionary<TimerState, ITimerState>(); m_InternalStates.Add(TimerState.Ready, new ReadyTimerState(this)); m_InternalStates.Add(TimerState.Sprint, new SprintTimerState(this)); m_InternalStates.Add(TimerState.HomeStraight, new HomeStraightTimerState(this)); m_InternalStates.Add(TimerState.Break, new BreakTimerState(this)); m_InternalStates.Add(TimerState.BreakOverrun, new BreakOverrunTimerState(this)); m_Timer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(1) }; m_Timer.Tick += (s, e) => m_InternalState.HandleSecondElapsed(); _State = TimerState.Ready; m_InternalState = m_InternalStates[_State]; m_InternalState.OnEnter(); }
// Use this for initialization void Start() { actualTimeRemaining = 0f; minutesRemaining = 0; secondsRemaining = 0; timerState = TimerState.PAUSED; gameManagerScript = gameManagerObject.GetComponent<GameManager>(); }
public static string GetStateString(TimerState state) { var formatString = " ({0}{1})"; var workOrBreak = state.ToString().Contains("Work") ? "work" : "break"; var paused = state.ToString().Contains("Pause") ? " paused" : ""; return string.Format(formatString, workOrBreak, paused); }
internal static void InvokeEventHandler(EventHandler<TimerStateChangedEventArgs> handler, object sender, TimerState previousState, TimerState newState) { var snapshot = handler; if (snapshot != null) { snapshot.DynamicInvoke(sender, new TimerStateChangedEventArgs(previousState, newState)); } }
public PerformanceTimer() { timerState = TimerState.Stopped; if (QueryPerformanceFrequency(ref tickFreq) == false) { throw new ApplicationException("Failed to query for the performance frequency!"); } }
public Timer() { this.interval = 10; this.loop = true; this.showCountDown = true; this.onClientElapsed = ""; this.finalSecondsBlink = false; this.finalSecondsThreshold = 0; this.timerState = TimerState.Started; }
/// <summary> /// Initializes a new instance of the <see cref="SimpleScheduler"/> class. /// </summary> /// <param name="applicationMapPath"> /// The application map path. /// </param> /// <param name="connection"> /// The connection. /// </param> /// <param name="period"> /// The period. /// </param> /// <remarks> /// </remarks> protected SimpleScheduler(string applicationMapPath, IDbConnection connection, long period) { this.localSchDB = new SchedulerDB(connection, applicationMapPath); this.localPeriod = period; this.localTimerState = new TimerState(); var t = new Timer(this.Schedule, this.localTimerState, Timeout.Infinite, Timeout.Infinite); this.localTimerState.Timer = t; }
public void Reset() { // Stop tracking and reset time timer.Stop(); TimerState = TimerState.Stopped; startTime = DateTime.Now; endTime = startTime; CalculateCurrentSpan(endTime, startTime); }
// Update is called once per frame void Update() { if (state == TimerState.Started) { timeRemaining -= Time.deltaTime; timerLabel.text = string.Format("Time Remaining: {0}", Mathf.RoundToInt(timeRemaining)); if (timeRemaining < 0f) { state = TimerState.Stopped; GameManager.Instance.OnOutOfTime(); } } }
public void Update(GameTime gameTime) { if(State!=TimerState.Running) return; CurrentTime += gameTime.ElapsedGameTime.TotalMilliseconds; if (CurrentTime >= TargetTime) { CurrentTime = 0; if (!Looping) State = TimerState.Finished; _callback(); } }
public RedditAuth(IWebAgent agent) { _uname = ConfigurationManager.AppSettings["BotUsername"]; _pass = ConfigurationManager.AppSettings["BotPassword"]; _clientId = ConfigurationManager.AppSettings["ClientID"]; _clientSecret = ConfigurationManager.AppSettings["ClientSecret"]; _redirectUri = ConfigurationManager.AppSettings["RedirectURI"]; if ( string.IsNullOrEmpty( _uname ) ) throw new Exception( "Missing 'BotUsername' in config" ); if ( string.IsNullOrEmpty( _pass ) ) throw new Exception( "Missing 'BotPassword' in config" ); if ( string.IsNullOrEmpty( _clientId ) ) throw new Exception( "Missing 'ClientID' in config" ); if ( string.IsNullOrEmpty( _clientSecret ) ) throw new Exception( "Missing 'ClientSecret' in config" ); if ( string.IsNullOrEmpty( _redirectUri ) ) throw new Exception( "Missing 'RedirectURI' in config" ); _webAgent = agent; _timerState = new TimerState(); }
public void ChangeState(TimerState state) { using (var session = DocumentStore.OpenSession()) { session.Store(new StateChangedEvent { Date = DateTimeOffset.Now, OldState = CurrentState, NewState = state }); session.SaveChanges(); } CurrentState = state; if (StateChanged != null) { StateChanged(state); } }
public void ToggleStartStop() { // Toggle tracking if (TimerState == TimerState.Stopped) { // Same behavior for reset and stop startTime = DateTime.Now; timer.Start(); TimerState = TimerState.Tracking; } else { endTime = DateTime.Now; timer.Stop(); // Call event that the time was tracked OnTimeTracked(); // Reset time after tracking Reset(); } }
public void ChangeState(TimerState state) { if(state == CurrentState) return; using (var session = DocumentStore.OpenSession()) { session.Store(new StateChangedEvent { MachineName = Environment.MachineName, Date = DateTimeOffset.Now, OldState = CurrentState, NewState = state }); session.SaveChanges(); } CurrentState = state; if (StateChanged != null) { StateChanged(state); } }
public Timer( Guid id, string name, string description, TimeSpan interval, TimerState state, TimeSpan elapsedTime, EventHandlerCollection eventHandlerCollection = null) { name.ThrowIfNull("name"); description.ThrowIfNull("description"); if (interval < TimeSpan.Zero) { throw new ArgumentOutOfRangeException("interval"); } _id = id; Name = name; Description = description; _interval = interval; _eventHandlerCollection = eventHandlerCollection; State = state; ElapsedTime = elapsedTime; }
public void Start() { mRunState = TimerState.Running; lastTick = DateTime.Now.Ticks; }
private void Tb_Idle() { if (_hasNewCrb) { switch (_tbState) { case TimerState.Stop: case TimerState.LoadThenStop: if ((_newCrb & 0x01) != 0) { _tbState = (_newCrb & 0x10) != 0 ? TimerState.LoadThenWaitThenCount : TimerState.WaitThenCount; } else { if ((_newCrb & 0x10) != 0) { _tbState = TimerState.LoadThenStop; } } break; case TimerState.Count: if ((_newCrb & 0x01) != 0) { if ((_newCrb & 0x10) != 0) { _tbState = TimerState.LoadThenWaitThenCount; } } else { _tbState = (_newCrb & 0x10) != 0 ? TimerState.LoadThenStop : TimerState.CountThenStop; } break; case TimerState.LoadThenCount: case TimerState.WaitThenCount: if ((_newCrb & 0x01) != 0) { if ((_newCrb & 0x08) != 0) { _newCrb &= 0xFE; _tbState = TimerState.Stop; } else if ((_newCrb & 0x10) != 0) { _tbState = TimerState.LoadThenWaitThenCount; } } else { _tbState = TimerState.Stop; } break; } _crb = _newCrb & 0xEF; _hasNewCrb = false; } }
public void Run() { Debug.Print("Starting RangeFinder in a separate thread..."); var rangeFinderProcess = new HC_SR04(Pins.GPIO_PIN_D0, Pins.GPIO_PIN_D1); OutputPort blueLED = new OutputPort(Pins.ONBOARD_LED, false); OutputPort greenLED = new OutputPort(Pins.GPIO_PIN_D13, false); TimerCallback proximityAlarmTimerCallback = new TimerCallback(ManageProximityAlarm); TimerCallback proximityAlarmClearHoldOffTimerCallback = new TimerCallback(ManageProximityAlarm); //Timer belowThresholdTimer = null; //Timer proximityAlarmClearHoldOffTimer = null; int belowThresholdCrossingCounter = 0; bool ledState = true; long pingResult; object setpoint; while (true) { belowThreshold = false; lock (monitor) { pingResult = rangeFinderProcess.Ping(); } Debug.Print("Reading = " + pingResult.ToString()); previousValue = currentValue; currentValue = pingResult; sourceBufferCurrentValue.HandlePut((object)currentValue); if (currentValue < currentLowTrigLevel) { Debug.Print("BELOW THRESHOLD!"); belowThreshold = true; if (previousValue > currentLowTrigLevel && belowThresholdTimerActive == false) { TimerState belowThresholdState = TimerState.belowThreshold; belowThresholdTimer = new Timer(proximityAlarmTimerCallback, belowThresholdState, lowTrigDur, (int)1.5 * lowTrigDur); belowThresholdTimerActive = true; belowThresholdCrossingCounter += 1; Debug.Print("Low Level Threshold Crossed (count=" + belowThresholdCrossingCounter.ToString() + ")"); Debug.Print("belowThresholdTimer Started (fires in " + lowTrigDur.ToString() + "ms)"); } if (proximityAlarmClearHoldOffTimerActive == true) { proximityAlarmClearHoldOffTimer.Dispose(); proximityAlarmClearHoldOffTimerActive = false; Debug.Print("proximityAlarmClearHoldOffTimer Cancelled"); } } else { belowThreshold = false; if (previousValue < currentLowTrigLevel && belowThresholdTimerActive == true) { belowThresholdTimer.Dispose(); belowThresholdTimerActive = false; Debug.Print("belowThresholdTimer Cancelled"); } if (previousValue < currentLowTrigLevel && proximityAlarmClearHoldOffTimerActive == false && belowThresholdCrossingCounter > 0) { proximityAlarmClearHoldOffTimerActive = true; TimerState holdingOffState = TimerState.holdingOff; proximityAlarmClearHoldOffTimer = new Timer(proximityAlarmClearHoldOffTimerCallback, holdingOffState, holdOffTime, (int)1.5 * holdOffTime); Debug.Print("proximityAlarmClearHoldOffTimer Started (fires in " + holdOffTime.ToString() + "ms)"); } } Thread.Sleep(period); setpoint = sourceBufferMeasPeriod.HandleGet(); if (setpoint != null) { period = (int)setpoint; period = period > 10000 ? 10000 : period; period = period < 100 ? 100 : period; if (period != currentPeriod) { Debug.Print("Period changed to " + period.ToString() + "ms"); } currentPeriod = period; } setpoint = sourceBufferLowTrigLevel.HandleGet(); if (setpoint != null) { int i = (int)setpoint; lowTrigLevel = (long)i; lowTrigLevel = lowTrigLevel > 3000L ? 3000L : lowTrigLevel; lowTrigLevel = lowTrigLevel < 100L ? 100L : lowTrigLevel; if (lowTrigLevel != currentLowTrigLevel) { Debug.Print("Low Trigger Level changed to " + lowTrigLevel.ToString() + "mm"); } currentLowTrigLevel = lowTrigLevel; } setpoint = sourceBufferLowTrigDur.HandleGet(); if (setpoint != null) { lowTrigDur = (int)setpoint; lowTrigDur = lowTrigDur > 10000 ? 10000 : lowTrigDur; lowTrigDur = lowTrigDur < 1000 ? 1000 : lowTrigDur; if (lowTrigDur != currentLowTrigDur) { Debug.Print("Low Trigger Duration changed to " + lowTrigDur.ToString() + "ms"); } currentLowTrigDur = lowTrigDur; } ledState = !ledState; blueLED.Write(ledState); greenLED.Write(ledState); } }
public void Reset() { _state = TimerState.Stopped; _duration = _originalDuration; }
public void Pause() { _state = TimerState.Paused; }
/// <summary> /// Creates a timer with a specified interval. /// </summary> /// <param name="interval"></param> public Timer(long interval, bool start) { timerInterval = interval; timerState = (!start) ? TimerState.Stopped : TimerState.Running; timer = new System.Threading.Timer(new TimerCallback(Tick), null, 0, interval); }
// A sentinel node - both the head and tail are one, which prevent the head and tail from ever having to be updated. internal TimerNode() : base(0) { _timerState = TimerState.Sentinel; }
public void Stop() { state = TimerState.STOPPED; }
// Start the timer (defer starting to "State" property) public void StartTimer() => State = TimerState.Started;
public Timer() { time = 1.0f; timerLimit = 1.0f; state = TimerState.READY; }
private void btnStartStop_Click(object sender, EventArgs e) { state = state.StartStop(); }
// private void MainForm_Load(object sender, EventArgs e) { state = new TimerStopped(this); }
/// <summary> /// Starts the timer instantly. /// </summary> public void Start() { timerState = TimerState.Running; timer.Change(0, timerInterval); }
public TimerStateChangedEventArgs(TimerState previousState, TimerState newState) { PreviousState = previousState; NewState = newState; }
/// <summary> /// Stops the timer. /// Note: Running threads won't be closed. /// </summary> public void Stop() { timerState = TimerState.Stopped; timer.Change(Timeout.Infinite, timerInterval); }
/// <summary> /// <para>Fires the timer if it is still active and has expired. Returns /// true if it can be deleted, or false if it is still timing.</para> /// </summary> internal bool Fire() { if (_timerState == TimerState.Sentinel) { if (NetEventSource.IsEnabled) { NetEventSource.Info(this, "TimerQueue tried to Fire a Sentinel."); } } if (_timerState != TimerState.Ready) { return(true); } // Must get the current tick count within this method so it is guaranteed not to be before // StartTime, which is set in the constructor. int nowMilliseconds = Environment.TickCount; if (IsTickBetween(StartTime, Expiration, nowMilliseconds)) { if (NetEventSource.IsEnabled) { NetEventSource.Info(this, $"TimerThreadTimer#{StartTime}::Fire() Not firing ({StartTime} <= {nowMilliseconds} < {Expiration})"); } return(false); } bool needCallback = false; lock (_queueLock) { if (_timerState == TimerState.Ready) { if (NetEventSource.IsEnabled) { NetEventSource.Info(this, $"TimerThreadTimer#{StartTime}::Fire() Firing ({StartTime} <= {nowMilliseconds} >= " + Expiration + ")"); } _timerState = TimerState.Fired; // Remove it from the list. Next.Prev = Prev; Prev.Next = Next; Next = null; Prev = null; needCallback = _callback != null; } } if (needCallback) { try { Callback callback = _callback; object context = _context; _callback = null; _context = null; callback(this, nowMilliseconds, context); } catch (Exception exception) { if (ExceptionCheck.IsFatal(exception)) { throw; } if (NetEventSource.IsEnabled) { NetEventSource.Error(this, $"exception in callback: {exception}"); } // This thread is not allowed to go into user code, so we should never get an exception here. // So, in debug, throw it up, killing the AppDomain. In release, we'll just ignore it. #if DEBUG throw; #endif } } return(true); }
// // Constructor // public Timer(bool isLooping = false) { this.isLooping = isLooping; state = TimerState.Stopped; }
public void Start() { _state = TimerState.Running; RunTimer(); }
private void ResetTimer() { timerState = TimerState.INIT; btnStart.Text = "Start"; seconds = 0; minutes = 0; hours = 0; TimerChanged.Invoke(this, new EventArgs()); txtSec.ReadOnly = false; // re-enable input txtMin.ReadOnly = false; txtHrs.ReadOnly = false; }
public void ExecutePhase() { _thisCnt = ReadCnt(); _taUnderflow = false; if (_taIrqNextCycle) { _taIrqNextCycle = false; TriggerInterrupt(1); } if (_tbIrqNextCycle) { _tbIrqNextCycle = false; TriggerInterrupt(2); } if (_taPrb6NegativeNextCycle) { _prb &= 0xBF; _taPrb6NegativeNextCycle = false; } if (_tbPrb7NegativeNextCycle) { _prb &= 0x7F; _tbPrb7NegativeNextCycle = false; } switch (_taState) { case TimerState.WaitThenCount: _taState = TimerState.Count; Ta_Idle(); break; case TimerState.Stop: Ta_Idle(); break; case TimerState.LoadThenStop: _taState = TimerState.Stop; _ta = _latcha; Ta_Idle(); break; case TimerState.LoadThenCount: _taState = TimerState.Count; _ta = _latcha; Ta_Idle(); break; case TimerState.LoadThenWaitThenCount: _taState = TimerState.WaitThenCount; if (_ta == 1) { Ta_Interrupt(); _taUnderflow = true; } else { _ta = _latcha; } Ta_Idle(); break; case TimerState.Count: Ta_Count(); break; case TimerState.CountThenStop: _taState = TimerState.Stop; Ta_Count(); break; } switch (_tbState) { case TimerState.WaitThenCount: _tbState = TimerState.Count; Tb_Idle(); break; case TimerState.Stop: Tb_Idle(); break; case TimerState.LoadThenStop: _tbState = TimerState.Stop; _tb = _latchb; Tb_Idle(); break; case TimerState.LoadThenCount: _tbState = TimerState.Count; _tb = _latchb; Tb_Idle(); break; case TimerState.LoadThenWaitThenCount: _tbState = TimerState.WaitThenCount; if (_tb == 1) { Tb_Interrupt(); } else { _tb = _latchb; } Tb_Idle(); break; case TimerState.Count: Tb_Count(); break; case TimerState.CountThenStop: _tbState = TimerState.Stop; Tb_Count(); break; } CountTod(); if (!_todLatch) { _latch10Ths = _tod10Ths; _latchSec = _todSec; _latchMin = _todMin; _latchHr = _todHr; } _flagInput = ReadFlag(); if (!_flagInput && _flagLatch) { TriggerInterrupt(16); } _flagLatch = _flagInput; if ((_cra & 0x02) != 0) { _ddra |= 0x40; } if ((_crb & 0x02) != 0) { _ddrb |= 0x80; } _lastCnt = _thisCnt; }
private void StopTimer() { t.Stop(); timerState = TimerState.STOPPED; btnStart.Text = "Reset"; }
public override void StopTimer() { _timer.Stop(); _timerState = TimerState.Stopped; }
public void Stop() { mRunState = TimerState.Stop; lastTick = long.MaxValue; }
public void Pause() { mRunState = TimerState.Pause; lastTick = long.MaxValue; }
/// <summary> /// 停止定时器 /// 注意:运行中的线程不会被停止 /// </summary> public void Stop() { timerState = TimerState.Stopped; timer.Change(Timeout.Infinite, timerInterval); }
public void Pause() { state = TimerState.PUASED; }
public async void StartWorkoutAsync() { try { this.currentWorkout = AppCore.CurrentWorkout; TimeSpan workoutSpan = GetWorkoutSpan(currentWorkout); List <TimeSpan> setSpans = new List <TimeSpan>(); //CancellationTokenSource src = new CancellationTokenSource(); //activeSources.Add(src); foreach (var set in currentWorkout.Timers) { for (int i = 0; i < set.Repetitions; i++) { //TimeSpan currentSetSpan = new TimeSpan(); foreach (var exercise in set.Timers) { for (int j = 0; j < exercise.Repetitions; j++) { // currentSetSpan = currentSetSpan.Add(exercise.Duration); //currentSetSpan = currentSetSpan.Add(new TimeSpan(0,0,1));//hax exerciseTimeSpans.Add(exercise.Duration); } } //setSpans.Add(set.Duration); setTimeSpans.Add(set.Duration); } } // CancellationToken ct = src.Token; currentSetTimer = new System.Timers.Timer(); currentSetTimer.Elapsed += (sender, e) => OnSetTimerFinishedEvent(this, new SetFinishedEventArgs()); currentWorkoutTimer.Elapsed += (sender, e) => OnWorkoutTimerFinishedEvent(this, new WorkoutFinishedEventArgs()); //setze auf ersten timer currentExerciseTimer.Interval = exerciseTimeSpans[0].Duration().TotalSeconds * 1000; currentSetTimer.Interval = setTimeSpans[0].Duration().TotalSeconds * 1000; currentWorkoutTimer.Interval = workoutSpan.Duration().TotalSeconds * 1000; StartAllTimers(); _timerState = TimerState.RUNNING; //var exerciseTask = await Task<bool>.Run(() => { // return RunExercise(ct); //},ct); //var setTask = await Task<bool>.Run(() => //{ // while (_timerState == TimerState.RUNNING) // { // while (setTimeSpans.Count > 0) // { // if (ct.IsCancellationRequested) // { // ct.ThrowIfCancellationRequested(); // } // //setTimer.Start(); // Task.Delay(setTimeSpans[0]).Wait(); // setTimeSpans.RemoveAt(0); // OnSetTimerFinishedEvent(this, new SetFinishedEventArgs(true)); // } // } // setTimer.Stop(); // return true; //},ct); ////TimeSpan setSpan = GetSetSpan(); ////int workoutSeconds = workoutSpan.TotalSeconds; //var workoutTask = await Task<bool>.Run(() => //{ // while (_timerState == TimerState.RUNNING) // { // if (ct.IsCancellationRequested) // { // ct.ThrowIfCancellationRequested(); // } // //workoutTimer.Start(); // Task.Delay(workoutSpan).Wait(); // OnWorkoutTimerFinishedEvent(this, new WorkoutFinishedEventArgs(true)); // } // workoutTimer.Stop(); // return true; //},ct); //exerciseTimer.Start(); //workoutTimer.Start(); //setTimer.Start(); //_timerState = TimerState.RUNNING; //workoutTask.ContinueWith(t => { int x = 0; }); //exerciseTask.ContinueWith(t => { int x = 0; }); //setTask.ContinueWith(t => { int x = 0; }); //Task.WaitAll(new[] { exerciseTask, setTask, workoutTask}); //Task.Run(() => exerciseTask); //Task.Run(() => workoutTask); //Task.Run(() => setTask); //exerciseTask.Start(); //setTask.Start(); //workoutTask.Start(); } catch (Exception ex) { throw ex; } }
/// <summary> /// Creates a timer with a specified interval, and starts after the specified delay. /// </summary> /// <param name="interval">Interval in milliseconds at which the timer will execute.</param> /// <param name="startDelay"></param> public Timer(long interval, int startDelay) { timerInterval = interval; timerState = (startDelay == Timeout.Infinite) ? TimerState.Stopped : TimerState.Running; timer = new System.Threading.Timer(new TimerCallback(Tick), null, startDelay, interval); }
public void Resume() { state = TimerState.RUNNING; }
/// <summary> /// Starts the timer with a specified delay. /// </summary> /// <param name="delayBeforeStart"></param> public void Start(int delayBeforeStart) { timerState = TimerState.Running; timer.Change(delayBeforeStart, timerInterval); }
/// <summary> /// 创建一个指定时间间隔的定时器,并在指定的延迟后开始启动。(默认间隔为100毫秒) /// </summary> public TimerHelper() { timerInterval = 100; timerState = TimerState.Stopped; timer = new System.Threading.Timer(new TimerCallback(Tick), null, Timeout.Infinite, timerInterval); }
/// <summary> /// Pauses the timer. /// Note: Running threads won't be closed. /// </summary> public void Pause() { timerState = TimerState.Paused; timer.Change(Timeout.Infinite, timerInterval); }
/// <summary> /// 创建一个指定时间间隔的定时器,并在指定的延迟后开始启动。 /// </summary> /// <param name="interval">定时器执行操作的间隔时间(毫秒)</param> /// <param name="startDelay">指定的延迟时间(毫秒)</param> public TimerHelper(long interval, int startDelay) { timerInterval = interval; timerState = (startDelay == Timeout.Infinite) ? TimerState.Stopped : TimerState.Running; timer = new System.Threading.Timer(new TimerCallback(Tick), null, startDelay, interval); }
public void Start() { State = TimerState.Started; Started.Raise(this, EventArgs.Empty); }
/// <summary> /// 创建一个指定时间间隔的定时器 /// </summary> /// <param name="interval">定时器执行操作的间隔时间(毫秒)</param> /// <param name="start">是否启动</param> public TimerHelper(long interval, bool start) { timerInterval = interval; timerState = (!start) ? TimerState.Stopped : TimerState.Running; timer = new System.Threading.Timer(new TimerCallback(Tick), null, 0, interval); }
public void Pause() { State = TimerState.Paused; Paused.Raise(this, EventArgs.Empty); }
/// <summary> /// 启动定时器并指定延迟时间(毫秒) /// </summary> /// <param name="delayBeforeStart">指定延迟时间(毫秒)</param> public void Start(int delayBeforeStart) { timerState = TimerState.Running; timer.Change(delayBeforeStart, timerInterval); }
private void RunTimer() { // input validation if (!(int.TryParse(txtSec.Text, out seconds)) || !(int.TryParse(txtMin.Text, out minutes)) || !(int.TryParse(txtHrs.Text, out hours))) { return; } txtSec.ReadOnly = true; // while timer runs txtMin.ReadOnly = true; txtHrs.ReadOnly = true; timerState = TimerState.STARTED; DecrementTimer(this, new EventArgs()); // don't want to wait a full second before starting countdown t.Start(); btnStart.Text = "Stop"; }
/// <summary> /// 立即启动定时器 /// </summary> public void Start() { timerState = TimerState.Running; timer.Change(0, timerInterval); }
private void TimerForm_Load(object sender, EventArgs e) { // Timer object fires once per second timerState = TimerState.INIT; t = new Timer(); t.Interval = 1000; t.Tick += DecrementTimer; // subscribe view TimerChanged += UpdateView; }
/// <summary> /// 暂停定时器 /// 注意:运行中的线程不会被停止 /// </summary> public void Pause() { timerState = TimerState.Paused; timer.Change(Timeout.Infinite, timerInterval); }