Exemplo n.º 1
0
    public static void Load()
    {
        if (File.Exists(RankingPath))
        {
            int index = 0;
            using (Stream stream = new FileStream(RankingPath, FileMode.Open, FileAccess.Read))
            {
                using (TextReader reader = new StreamReader(stream))
                {
                    for (int i = 0; i < 3; ++i)
                    {
                        string elapsed  = reader.ReadLine();
                        string recorded = reader.ReadLine();

                        rank [index++] = new Elapsed()
                        {
                            ElapsedTime = TimeSpan.FromTicks(int.Parse(elapsed)),
                            Recorded    = DateTime.Parse(recorded)
                        };
                    }
                }
            }
            Debug.Log("Ranking file loaded from " + RankingPath);
        }
    }
        private void TimerElapsedHandler(object sender, ElapsedEventArgs e)
        {
            _updateTime = _updateTime.AddDays(1.0);
            CalculateTimerInterval();

            Elapsed?.Invoke(sender, e);
        }
Exemplo n.º 3
0
        /// <summary>
        /// This method is called by _taskTimer.
        /// </summary>
        /// <param name="state">Not used argument</param>
        private void TimerCallBack(object state)
        {
            lock (_taskTimer)
            {
                if (!_isRunning || _performingTasks)
                {
                    return;
                }

                _taskTimer.Change(Timeout.Infinite, Timeout.Infinite);
                _performingTasks = true;
            }

            try
            {
                Elapsed?.Invoke(this, new EventArgs());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                lock (_taskTimer)
                {
                    _performingTasks = false;
                    if (_isRunning)
                    {
                        _taskTimer.Change(Period, Timeout.Infinite);
                    }

                    Monitor.Pulse(_taskTimer);
                }
            }
        }
Exemplo n.º 4
0
    IEnumerator DespawnTimeout(float seconds)
    {
        yield return(new WaitForSeconds(seconds));

        Elapsed?.Invoke(this);
        GameObject.Destroy(gameObject);
    }
Exemplo n.º 5
0
 public override bool OnIntervalClose()
 {
     if (Next.Position.IsFlat || Next.Position.IsLong)
     {
         diff[0] = Bars.Typical[0] - slowAvg[0];
         if (diff[0] < -lowTrigger)
         {
             Orders.Enter.ActiveNow.BuyMarket();
         }
         if (diff[0] > highTrigger)
         {
             Orders.Exit.ActiveNow.GoFlat();
         }
         Elapsed span = Position.Time - Bars.Time[0];
         if (span.TotalHours > maxHours)
         {
             Orders.Exit.ActiveNow.GoFlat();
         }
     }
     else
     {
         Orders.Exit.ActiveNow.GoFlat();
     }
     return(true);
 }
Exemplo n.º 6
0
 public void Tick()
 {
     if (Enabled)
     {
         Elapsed?.Invoke(0, 0);
     }
 }
Exemplo n.º 7
0
        private void ThreadMain()
        {
            float nextNotification = 0;
            float elapsedMilliseconds;

            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();

            while (this.runTimer)
            {
                nextNotification += Interval;

                while ((elapsedMilliseconds = (float)stopWatch.Elapsed.TotalMilliseconds)
                       < nextNotification)
                {
                    Thread.Yield();
                }

                if (elapsedMilliseconds - nextNotification >= IgnoreEventIfLateBy)
                {
                    continue;
                }
                Elapsed?.Invoke();
            }

            stopWatch.Stop();
        }
Exemplo n.º 8
0
        /// <summary>
        /// _taskTimer调用
        /// </summary>
        /// <param name="state">暂未使用该参数</param>
        private void TimerCallBack(object state)
        {
            lock (_taskTimer) {
                if (!_isRunning || _performingTasks)
                {
                    return;
                }

                _taskTimer.Change(Timeout.Infinite, Timeout.Infinite);
                _performingTasks = true;
            }

            try {
                Elapsed.InvokeSafely(this, new EventArgs());
            } catch (Exception ex) {
                Logger.LogException(ex);
                AsyncHelper.RunSync(() => ExceptionNotifier.NotifyAsync(ex));
            } finally {
                lock (_taskTimer) {
                    _performingTasks = false;
                    if (_isRunning)
                    {
                        _taskTimer.Change(Period, Timeout.Infinite);
                    }

                    Monitor.Pulse(_taskTimer);
                }
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// This method is called by _taskTimer.
        /// </summary>
        /// <param name="state">Not used argument</param>
        private void TimerCallBack(object state)
        {
            lock (_timer)
            {
                if (!_isRunning || _performingTasks)
                {
                    return;
                }

                _timer.Change(Timeout.Infinite, Timeout.Infinite);
                _performingTasks = true;
            }

            try
            {
                Elapsed.InvokeSafely(this, new EventArgs());
            }
            catch
            {
            }
            finally
            {
                lock (_timer)
                {
                    _performingTasks = false;
                    if (_isRunning)
                    {
                        _timer.Change(Period, Timeout.Infinite);
                    }

                    Monitor.Pulse(_timer);
                }
            }
        }
Exemplo n.º 10
0
 public void ElapsedAction()
 {
     if (Elapsed != null)
     {
         Elapsed.Invoke(this, null);
     }
 }
Exemplo n.º 11
0
        private void OnElapsed(object source, ElapsedEventArgs e)
        {
            Elapsed?.Invoke(this, EventArgs.Empty);

            // reset timer in case we modified it by Delay
            timer.Interval = interval;
        }
Exemplo n.º 12
0
        private void TimerCallBack(object state)
        {
            lock (_taskTimer) {
                if (!_running || _performingTasks)
                {
                    return;
                }

                _taskTimer.Change(Timeout.Infinite, Timeout.Infinite);
                _performingTasks = true;
            }

            var elapsedEventArgs = state as ElapsedEventArgs;

            try {
                Elapsed?.Invoke(this, elapsedEventArgs);
            } catch (Exception e) {
                Console.WriteLine(e);
            } finally {
                lock (_taskTimer) {
                    _performingTasks = false;
                    if (_running)
                    {
                        _taskTimer.Change(Period, Timeout.Infinite);
                    }

                    Monitor.Pulse(_taskTimer);
                }
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// This method is called by _taskTimer.
        /// </summary>
        /// <param name="state">Not used argument</param>
        private void timerCallBack(object state)
        {
            lock (_lock)
            {
                if (!_running || _performingTasks)
                {
                    return;
                }

                _taskTimer.Change(Timeout.Infinite, Timeout.Infinite);
                _performingTasks = true;
            }

            try
            {
                Elapsed?.Invoke(this, EventArgs.Empty);
            }
            finally
            {
                lock (_lock)
                {
                    _performingTasks = false;
                    if (_running)
                    {
                        _taskTimer.Change(Period, Timeout.Infinite);
                    }

                    Monitor.Pulse(_taskTimer);
                }
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// This method is called by _taskTimer.
        /// </summary>
        /// <param name="state">Not used argument</param>
        private void TimerCallBack(object state)
        {
            _taskTimer.Locking(t =>
            {
                if (!_isRunning || _performingTasks)
                {
                    return;
                }

                t.Change(Timeout.Infinite, Timeout.Infinite);
                _performingTasks = true;
            }
                               );
            try
            {
                Elapsed.Invoke(this, new EventArgs());
            }
            catch
            {
                //do nothing.
            }
            finally
            {
                _taskTimer.Locking(t =>
                {
                    _performingTasks = false;
                    if (_isRunning)
                    {
                        t.Change(Period, Timeout.Infinite);
                    }

                    Monitor.Pulse(_taskTimer);
                });
            }
        }
Exemplo n.º 15
0
        private void Callback(object state)
        {
            lock (this) {
                _tickCount++;

                Elapsed?.Invoke(this, TimeSpan.FromMilliseconds(_tickCount * Period.TotalMilliseconds));

                var elapsed = DateTime.Now - _startAt;

                var millisShouldBe = _tickCount * Period.TotalMilliseconds;
                var millisIs       = elapsed.TotalMilliseconds;
                var timeDiff       = millisShouldBe - millisIs;
                if (timeDiff > Period.TotalMilliseconds)
                {
                    timeDiff = Period.TotalMilliseconds;
                }
                if (timeDiff < -Period.TotalMilliseconds)
                {
                    timeDiff = -Period.TotalMilliseconds;
                }

                if (_enabled)
                {
                    _timer.Change(
                        (int)(Period.TotalMilliseconds + timeDiff),
                        (int)Period.TotalMilliseconds
                        );
                }
            }
        }
Exemplo n.º 16
0
Arquivo: Timer.cs Projeto: oldas1/ztm
        async void OnElapsed(object context)
        {
            if (!this.stopGuard.TryLock())
            {
                return;
            }

            try
            {
                await Elapsed.InvokeAsync(this, new TimerElapsedEventArgs(context, CancellationToken.None));
            }
            finally
            {
                Interlocked.Increment(ref this.elapsed);

                this.stopGuard.Release();

                // Try to change one-shot state to 3 (stopping by inside) only if it is 1 (one-shot not fired). If the
                // current value is 1 that mean this method have responsibility to clean up resources.
                if (Interlocked.CompareExchange(ref this.oneShotState, 3, 1) == 1)
                {
                    Stop();
                }
            }
        }
Exemplo n.º 17
0
 public Timer()
 {
     base.Elapsed += (o, e) =>
     {
         Elapsed?.Invoke(this, EventArgs.Empty);
     };
 }
Exemplo n.º 18
0
        private void ThreadLoop()
        {
            while (_threadLoopEnabled)
            {
                // If we are not enabled, or we have more than the CoarseSleepThreshold ms left until we need to invoke, sleep for 1 ms
                while (_threadLoopEnabled &&
                       (!_elapsedEventEnabled ||
                        _stopwatch.ElapsedMilliseconds + CoarseSleepThreshold < _nextInvoke))
                {
                    Thread.Sleep(1);
                }
                // If we are not yet ready to invoke, then be kind to other threads & let them have some pie, but don't sleep as we are close
                while (_threadLoopEnabled && _stopwatch.ElapsedMilliseconds < _nextInvoke)
                {
                    Thread.Sleep(0);
                }
                if (_threadLoopEnabled && _elapsedEventEnabled)
                {
                    long time = _stopwatch.ElapsedMilliseconds;
                    this.TimeSinceLastTick = time - _lastTick;
                    _lastTick = time;
                    Elapsed?.Invoke(null, null);

                    _nextInvoke = time + (int)this.Interval;
                }
            }
        }
Exemplo n.º 19
0
        private void ElapsedThreadProc()
        {
            while (true)
            {
                m_waitHandle.WaitOne();

                if (m_disposing)
                {
                    return;
                }

                ElapsedEventArgs eea = new ElapsedEventArgs(DateTime.Now);

                if (Elapsed != null)
                {
                    foreach (ElapsedEventHandler eeh in Elapsed.GetInvocationList())
                    {
                        // determine if we're supposed to Invoke or not
                        if (SynchronizingObject == null)
                        {
                            eeh(this, eea);
                        }
                        else
                        {
                            SynchronizingObject.Invoke(eeh, new object[] { this, eea });
                        }
                    }
                }
            }
        }
Exemplo n.º 20
0
 /// <summary>
 /// If there are any subscribers - raise the Elapsed event.
 /// </summary>
 /// <param name="sender">the sender to include within the event's event-args</param>
 internal void InvokeElapsed(object sender)
 {
     if (Elapsed != null)
     {
         Elapsed.Invoke(sender, m_timerEventArgs);
     }
 }
Exemplo n.º 21
0
        public void Update(long deltaTime)
        {
            // Nothing to do
            if (!IsActive)
            {
                return;
            }

            // Decrement remaining time
            if (Remaining > 0)
            {
                Remaining -= deltaTime;
            }

            if (Remaining <= 0)
            {
                // No more remaining time for this slice
                --Value;
                Elapsed?.Invoke(this, EventArgs.Empty);

                if (Value != 0)
                {
                    // Subtract current remaining time from specified interval because it can be negative
                    Remaining = Interval - Remaining;
                }
                else
                {
                    // We're done!
                    Stopped?.Invoke(this, EventArgs.Empty);
                    Remaining = 0;
                }
            }
        }
Exemplo n.º 22
0
 private void AdjustSessions()
 {
     foreach (var kvp in symbolMap)
     {
         string           symbol           = kvp.Key;
         SymbolProperties symbolProperties = kvp.Value;
         if (symbolProperties.TimeZone == null || symbolProperties.TimeZone.Length == 0)
         {
             continue;
         }
         if (symbolProperties.DisplayTimeZone == "Local" ||
             symbolProperties.DisplayTimeZone == "UTC")
         {
             // Convert session times from Exchange to UTC.
             SymbolTimeZone timeZone = new SymbolTimeZone(symbolProperties);
             timeZone.SetExchangeTimeZone();
             int     startOffset     = (int)timeZone.UtcOffset(new TimeStamp());
             int     endOffset       = (int)timeZone.UtcOffset(new TimeStamp());
             Elapsed utcSessionStart = symbolProperties.SessionStart - new Elapsed(0, 0, startOffset);
             Elapsed utcSessionEnd   = symbolProperties.SessionEnd - new Elapsed(0, 0, endOffset);
             // Convert UTCI session times to either Local or UTC as chosen
             // by the DisplayTimeZone property.
             timeZone    = new SymbolTimeZone(symbolProperties);
             startOffset = (int)timeZone.UtcOffset(new TimeStamp());
             endOffset   = (int)timeZone.UtcOffset(new TimeStamp());
             symbolProperties.SessionStart = utcSessionStart + new Elapsed(0, 0, startOffset);
             symbolProperties.SessionEnd   = utcSessionEnd + new Elapsed(0, 0, endOffset);
         }
     }
 }
Exemplo n.º 23
0
        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Elapsed = Elapsed.Add(TimeSpan.FromSeconds(1));

            if (CurrentActivity == Activity.Working && Elapsed.TotalSeconds >= config.Working * 60)
            {
                AddHistory(Elapsed.TotalMinutes, true);
                pomodoros++;
                if (pomodoros == config.Pomorodos)
                {
                    ChangeState(Activity.LongBreak);
                }
                else
                {
                    ChangeState(Activity.ShortBreak);
                }
            }

            if ((CurrentActivity == Activity.ShortBreak && Elapsed.TotalSeconds >= config.ShortBreak * 60) ||
                (CurrentActivity == Activity.LongBreak && Elapsed.TotalSeconds >= config.LongBreak * 60))
            {
                AddHistory(Elapsed.TotalMinutes, false);
                ChangeState(Activity.Working);
            }
        }
        /// <summary>
        /// Actual deconstructor in accordance with the dispose pattern
        /// </summary>
        /// <param name="disposing">
        /// True if managed and unmanaged resources will be freed
        /// (otherwise only unmanaged resources are handled)
        /// </param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                disposed = true;
                if (disposing)
                {
                    Delegate[] delegateBuffer = null;

                    monitorTimer.Elapsed -= new ElapsedEventHandler(TimerElapsed);
                    monitorTimer.Dispose();

                    delegateBuffer = Elapsed.GetInvocationList();
                    foreach (ElapsedEventHandler item in delegateBuffer)
                    {
                        Elapsed -= item;
                    }
                    Elapsed = null;

                    delegateBuffer = Reactivated.GetInvocationList();
                    foreach (EventHandler item in delegateBuffer)
                    {
                        Reactivated -= item;
                    }
                    Reactivated = null;
                }
            }
        }
Exemplo n.º 25
0
        public override bool OnProcessTick(Tick tick)
        {
            Elapsed ts = tick.Time - Range5.Time[0];

            equity[0] = Performance.Equity.CurrentEquity;
            return(true);
        }
Exemplo n.º 26
0
 public unsafe void Start()
 {
     lock (stateLock)
     {
         if (!Enabled)
         {
             if (IsSupportedNatively(Interval))
             {
                 var caps = new TimeCaps();
                 _ = timeGetDevCaps(ref caps, (uint)sizeof(TimeCaps));
                 var clampedInterval = Math.Clamp((uint)Interval, caps.wPeriodMin, caps.wPeriodMax);
                 _       = timeBeginPeriod(clampedInterval);
                 timerId = timeSetEvent(clampedInterval, 1, callbackDelegate, IntPtr.Zero, EventType.TIME_PERIODIC | EventType.TIME_KILL_SYNCHRONOUS);
                 Enabled = true;
             }
             else
             {
                 Log.Write("Timer", "Unsupported interval detected, will use fallback timer. Expect high CPU usage", LogLevel.Warning);
                 fallbackTimer = new FallbackTimer
                 {
                     Interval = Interval
                 };
                 fallbackTimer.Elapsed += () => Elapsed?.Invoke();
                 fallbackTimer.Start();
                 Enabled = true;
             }
         }
     }
 }
        private void ExecuteTimer()
        {
            float nextTrigger = 0f;

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            while (isRunning)
            {
                nextTrigger += interval;
                float elapsed;

                while (true)
                {
                    elapsed = ElapsedHiRes(stopwatch);
                    float diff = nextTrigger - elapsed;
                    if (diff <= 0f)
                    {
                        break;
                    }

                    if (diff < 1f)
                    {
                        Thread.SpinWait(10);
                    }
                    else if (diff < 5f)
                    {
                        Thread.SpinWait(100);
                    }
                    else if (diff < 15f)
                    {
                        Thread.Sleep(1);
                    }
                    else
                    {
                        Thread.Sleep(10);
                    }

                    if (!isRunning)
                    {
                        return;
                    }
                }


                float delay = elapsed - nextTrigger;
                Elapsed?.Invoke(delay);

                // restarting the timer in every hour to prevent precision problems
                if (stopwatch.Elapsed.TotalHours >= 1d)
                {
                    stopwatch.Restart();
                    nextTrigger = 0f;
                }
            }

            stopwatch.Stop();
        }
Exemplo n.º 28
0
 private void baseElapsed(object sender, object e)
 {
     if (!AutoReset)
     {
         Stop();
     }
     Elapsed?.Invoke(this, new EventArgs());
 }
Exemplo n.º 29
0
 public void Tick()
 {
     if ((Time -= GameTime.DeltaTime) <= 0)
     {
         Time += Interval;
         Elapsed.Invoke(this, new TimerElapsedEventArgs());
     }
 }
Exemplo n.º 30
0
 public new void Start()
 {
     Stopped = false;
     if (!EnableOverride && Enabled && Elapsed != null)
     {
         Elapsed.Invoke(this, new EventArgs() as ElapsedEventArgs);
     }
 }