/** * Starts raising the Elapsed event by setting Enabled to true. * You can also start timing by setting Enabled to true. */ public void Start() { #if NETFX_CORE enabled = true; if (!running) { TimerElapsedHandler handler = (t) => { if (AutoReset) { throw new NotImplementedException("If autoreset == true and enabled == true," + " the timer is supposed to restart."); } if (Enabled) { Elapsed(null, new ElapsedEventArgs()); } }; timer = ThreadPoolTimer.CreatePeriodicTimer(handler, timeSpan); running = true; } #else throw new PlatformNotSupportedException(); #endif }
public async void Run(IBackgroundTaskInstance taskInstance) { taskInstance.Canceled += TaskInstance_Canceled; Deferral = taskInstance.GetDeferral(); await LogAsync($"Start {DateTime.Now}"); Handler = new TimerElapsedHandler(PoolTimerCallback); PoolTimer = ThreadPoolTimer.CreateTimer(Handler, Delay); }
public MyTimer(SynchronizationContext synchronizationContext) { if (this.synchronizationContext == null) { throw new ArgumentNullException("No synchronization context was specified and no default synchronization context was found.") } TimerElapsedHandler f = new TimerElapsedHandler(NotifyTimeChanged); TimeSpan period = new TimeSpan(0, 0, 1); ThreadPoolTimer.CreatePeriodicTimer(f, period); }
public Hospital() { this.InitializeComponent(); HospitalChoose.IsChecked = true; VaccinationChoose.IsChecked = false; ShowCenterLocation(); listAdd = pAdd.GetListObject(1); TimeSpan timeSpan = new TimeSpan(0, 0, 8); var handler = new TimerElapsedHandler(UpdateTimer); ThreadPoolTimer threadPool = ThreadPoolTimer.CreatePeriodicTimer(handler, timeSpan); }
public ThreadPoolTimer(TimerElapsedHandler handler, TimeSpan period, TimerDestroyedHandler destroyed) { _handler = handler; _destroyed = destroyed; newTimer = new DispatcherTimer(); // timer interval specified as 1 second newTimer.Interval = TimeSpan.FromSeconds(1); // Sub-routine OnTimerTick will be called at every 1 second newTimer.Tick += delegate(object sender, EventArgs args) { _handler(this); }; // starting the timer newTimer.Start(); }
internal ThreadPoolTimer(TimerElapsedHandler handler, TimeSpan?period = null, TimeSpan?delay = null, TimerDestroyedHandler destroyed = null) { _timer = new Timer(_ => { if (!_cts.IsCancellationRequested) { handler.Invoke(this); } }); _destroyed = destroyed; _timer.Change( period: period ?? global::System.Threading.Timeout.InfiniteTimeSpan, dueTime: delay ?? global::System.Threading.Timeout.InfiniteTimeSpan ); }
/// <summary> /// Starts the location tracking by using system timer. /// </summary> private void StartLocationIntervalTracking() { var activityDetail = this.SupportedActivityTypes.First(x => x.ActivityType == this.SelectedActivity); this.isFetchingLocation = false; var handler = new TimerElapsedHandler(this.LocationFechingTimer_Tick); if (this.trackingMechanism == TrackingMechanism.LocationFetchingTimer) { this.locationFechingTimer = ThreadPoolTimer.CreatePeriodicTimer(handler, TimeSpan.FromSeconds(activityDetail.TrackingInterval)); } else if (this.trackingMechanism == TrackingMechanism.Hybrid) { this.locationFechingTimer = ThreadPoolTimer.CreatePeriodicTimer(handler, TimeSpan.FromSeconds(activityDetail.TrackingInterval / 2)); } // Don't wait for timer to tick. this.LocationFechingTimer_Tick(null); }
public TimerHandler(TimerElapsedHandler handler, TimeSpan period, TimerDestroyedHandler destroyed) { _periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(handler, period, destroyed); }
/// <summary> /// Creates a single-use timer. /// </summary> /// <param name="handler">The method to call when the timer expires.</param> /// <param name="delay">The number of milliseconds until the timer expires.</param> /// <returns>An instance of a single-use timer.</returns> public static ThreadPoolTimer CreateTimer(TimerElapsedHandler handler, TimeSpan delay) { return CreateTimer(handler, delay, destroyed: null); }
public static ThreadPoolTimer CreateTimer(TimerElapsedHandler handler, TimeSpan delay, TimerDestroyedHandler destroyed) => new ThreadPoolTimer(handler, delay: delay, destroyed: destroyed);
/// <summary> /// This method will try to establish a connection to the Blynk server. /// </summary> /// <returns>'True' if a connection is established, 'False' if not.</returns> public bool Connect() { bool result = false; int connectTimeoutMilliseconds = 1000; try { tcpClient = new TcpClient(); tcpClient.NoDelay = true; var connectionTask = tcpClient.ConnectAsync(Server, Port).ContinueWith(task => { return(task.IsFaulted ? null : tcpClient); }, TaskContinuationOptions.ExecuteSynchronously); var timeoutTask = Task.Delay(connectTimeoutMilliseconds).ContinueWith <TcpClient>(task => null, TaskContinuationOptions.ExecuteSynchronously); var resultTask = Task.WhenAny(connectionTask, timeoutTask).Unwrap(); resultTask.Wait(); var resultTcpClient = resultTask.Result; if (resultTcpClient != null) { tcpStream = tcpClient.GetStream(); txMessageId = 1; List <byte> txMessage = new List <byte>() { 0x02 }; txMessage.Add(( byte )(txMessageId >> 8)); txMessage.Add(( byte )(txMessageId)); txMessage.Add(( byte )(Authentication.Length >> 8)); txMessage.Add(( byte )(Authentication.Length)); foreach (char c in Authentication) { txMessage.Add(( byte )c); } tcpStream.Write(txMessage.ToArray(), 0, txMessage.Count); readTcpStream(); connected = true; Task.Run(new Action(blynkReceiver)); result = true; } else { // Not connected } } catch (Exception) { } // Create a timer to handle the ping/reconnection period TimerElapsedHandler blynkTimerElapsedTimer = new TimerElapsedHandler(timer_Tick); blynkTimer = ThreadPoolTimer.CreatePeriodicTimer(timer_Tick, new TimeSpan(0, 0, 5)); return(result); }
public void OnElapse(TimerElapsedHandler e) { Elapsed += e; }
/// <summary> /// Creates a periodic timer. /// </summary> /// <param name="handler">The method to call when the timer expires.</param> /// <param name="period"> /// The number of milliseconds until the timer expires. /// The timer reactivates each time the period elapses, until the timer is canceled. /// </param> /// <returns>An instance of a periodic timer.</returns> public static ThreadPoolTimer CreatePeriodicTimer(TimerElapsedHandler handler, TimeSpan period) { return CreatePeriodicTimer(handler, period, destroyed: null); }
private ThreadPoolTimer(TimerElapsedHandler handler, TimerDestroyedHandler destroyed, TimeSpan delay, bool isPeriodic) { Delay = delay; if (isPeriodic) Period = delay; this.isPeriodic = isPeriodic; this.handler = handler; this.destroyed = destroyed; this.realTimer = new Timer(t => { var ltimer = (ThreadPoolTimer)t; lock (ltimer) { if (ltimer.isCanceled) return; ltimer.isRunning = true; } Task.Factory.StartNew(o => { ThreadPoolTimer taskedTimer = (ThreadPoolTimer)o; try { taskedTimer.handler(taskedTimer); } finally { lock (ltimer) { taskedTimer.isRunning = false; if (!taskedTimer.isPeriodic || taskedTimer.isCanceled) ltimer.Cancel(); } } }, ltimer); }, this, (int)delay.TotalMilliseconds, (isPeriodic) ? (int)delay.TotalMilliseconds : Timeout.Infinite); }
/// <summary> /// Creates a single-use timer and specifies a method to call after the timer is complete. /// The timer is complete when the timer has expired and the final call to handler has finished. /// </summary> /// <param name="handler">The method to call when the timer expires.</param> /// <param name="delay">The number of milliseconds until the timer expires.</param> /// <param name="destroyed">The method to call after the timer is complete.</param> /// <returns>An instance of a single-use timer.</returns> public static ThreadPoolTimer CreateTimer(TimerElapsedHandler handler, TimeSpan delay, TimerDestroyedHandler destroyed) { if (handler == null) throw new ArgumentException("handler"); return new ThreadPoolTimer(handler, destroyed, delay, isPeriodic: false); }
public static ThreadPoolTimer CreateTimer(TimerElapsedHandler handler, TimeSpan delay) => new ThreadPoolTimer(handler, delay: delay);
public static ThreadPoolTimer CreatePeriodicTimer(TimerElapsedHandler handler, TimeSpan period, TimerDestroyedHandler destroyed) => new ThreadPoolTimer(handler, period: period, destroyed: destroyed);
public static ThreadPoolTimer CreatePeriodicTimer(TimerElapsedHandler handler, TimeSpan period, TimerDestroyedHandler destroyed) { return new ThreadPoolTimer(handler,period,destroyed); }
// // Initializes rpcclient and metering // internal async Task StartMetering(int sampleRate) { await Task.Run(() => { rpcClient = IntPtr.Zero; SampleMessage = ""; StartButtonEnabled = false; StopButtonEnabled = true; stopMeteringRequested = false; if (NotifyIfAnyError(RpcClientInitialize(out rpcClient))) { return; } meteringOn = true; sampleRefreshCount = 0; sampleArray[0] = 0; // Set the sample rate on server samplePeriod = sampleRate; long retCode = SetSampleRate(rpcClient, sampleRate); FILETIME initialSystemTime = new FILETIME(); GetSystemTimeAsFileTime(ref initialSystemTime); lastUpdateTime = new LARGE_INTEGER(); lastUpdateTime.LowPart = initialSystemTime.dwLowDateTime; lastUpdateTime.HighPart = initialSystemTime.dwHighDateTime; if (!NotifyIfAnyError(retCode)) { // Set up worker for UI update. TimeSpan span = new TimeSpan(100 * 10000); // 100ms refresh rate TimerElapsedHandler timerHandler = (ThreadPoolTimer) => { long meteringData = 0; GetMeteringData(rpcClient, ref meteringData); // If there is no new data, return if (sampleArray[0] == meteringData) { return; } // Arithmetic subtraction of time // https://msdn.microsoft.com/en-us/library/ms724950%28VS.85%29.aspx FILETIME currentSystemTime = new FILETIME(); LARGE_INTEGER currentTimeUi = new LARGE_INTEGER(); GetSystemTimeAsFileTime(ref currentSystemTime); currentTimeUi.LowPart = currentSystemTime.dwLowDateTime; currentTimeUi.HighPart = currentSystemTime.dwHighDateTime; // Calculate number of samples received since last callback long now = 0, diff = 0; GetCallbackCount(rpcClient, ref now); diff = now - rpcDataCountOld; rpcDataCountOld = now; // Calculate incoming sample rate double rate = (double)diff * 1E7 / (currentTimeUi.QuadPart - lastUpdateTime.QuadPart); ExpectedRpcCallbackRate = (1E3 / samplePeriod).ToString() + " /sec"; lastUpdateTime = currentTimeUi; ActualRpcCallbackRate = rate.ToString() + " /sec"; // Construct the sample data string string sampleMessage = meteringData + "\n"; uint length = (uint)sampleArray.Length; if (sampleRefreshCount < length) { ++sampleRefreshCount; length = sampleRefreshCount; } // Insert the new data point at the top of the array. // Old data falls off the end of the array. for (int i = 1; i < length; ++i) { sampleArray[i] = sampleArray[i - 1]; sampleMessage += sampleArray[i] + "\n"; } sampleArray[0] = meteringData; SampleMessage = sampleMessage; }; ThreadPoolTimer periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(timerHandler, span); NotifyStatusMessage("Metering start command sent successfully", NotifyType.StatusMessage); retCode = StartMeteringAndWaitForStop(rpcClient, sampleRate); meteringOn = false; periodicTimer.Cancel(); if (!NotifyIfAnyError(retCode) && !stopMeteringRequested) { NotifyStatusMessage("Rpc server connection closed without stop metering being requested", NotifyType.ErrorMessage); StartButtonEnabled = true; StopButtonEnabled = false; } RpcClientClose(rpcClient); } }); }
private void StartThreadPoolTimer() { var timerElapseHandler = new TimerElapsedHandler((arg) => { GetReading(); }); threadPoolTimer = ThreadPoolTimer.CreatePeriodicTimer(timerElapseHandler, timeSpanDelay); }