public void PercentageComplete(int elapsedSeconds, double expectedPercentage) { _sut.StartCountdown(1, false); while (_callBackList.Last().TotalSeconds > elapsedSeconds) { _timerFacadeCallback.Invoke(null); } Assert.AreEqual(expectedPercentage, _sut.PercentageToGo); }
public void Countdown_end_triggers_noise_when_enabled() { _sut.StartCountdown(1, true); for (var i = 0; i < 59; i++) { _timerFacadeCallback.Invoke(null); } A.CallTo(() => _fakeSoundProvider.MakeSound()).MustNotHaveHappened(); _timerFacadeCallback?.Invoke(null); A.CallTo(() => _fakeSoundProvider.MakeSound()).MustHaveHappened(); }
/// <summary> 增加间隔时间 </summary> private void addInterval(float deltaTime) { currentTime += deltaTime; if (currentTime < delay) { return; } if (currentTime - lastTime >= interval) { currentCount++; lastTime = currentTime; if (repeatCount <= 0) { // 无限重复 if (currentCount == int.MaxValue) { reset(); } // 每计数间隔都执行一次的函数 // 这里两个方法都通知调用(这两种只是绑定方法的方式不一样而已) // // 第一个是用户通过 start 方法传入的回调函数, // 第二个是通过在编辑器界面指定调用的方法) onIntervalCall?.Invoke(this); onIntervalEvent?.Invoke(); } else { if (currentCount < repeatCount) { //计时间隔 onIntervalCall?.Invoke(this); onIntervalEvent?.Invoke(); } else { //计时结束 stop(); onCompleteCall?.Invoke(this); onCompleteEvent?.Invoke(); if (autoDestory && !enabled) { Destroy(this); } } } } }
public override Timer CreateTimer(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period) { //immediately invoke callback callback.Invoke(state); //move the due time to some distant point in the future return(base.CreateTimer(callback, state, new TimeSpan(10, 0, 0, 0), period)); }
public void StartMonitoring() { TimerCallback timerDelegate = new TimerCallback(CheckIEURL); timer = new System.Threading.Timer(timerDelegate, null, 0, 1000); timerDelegate.Invoke(new object()); }
private void CallbackFunc(object state) { //只运行一次 this.Stop(); _callback?.Invoke(state); }
public void Tick(float time) { if (IsProgramPaused) { return; } if (!IsDone && !IsPaused) { //Debug.Log(ElapsedTime + " -- " + Time + " -- " + Callback); ElapsedTime += time; IsDone = ElapsedTime >= Time; if (IsDone) { ElapsedTime = Time; //Debug.Log("CALLING CALLBACK"); Callback?.Invoke(); } else { OnTick?.Invoke(this); } } else { } }
private void TimerThreadCallback(TimerCallback timerCallback) { ThreadStart threadStart = new ThreadStart(() => { Thread.Sleep(_Period); lock (_Lock) { if (_IsRunning) {// we have to check whether we are still running, otherwise we might end up sending this signal for a new thread start Monitor.Pulse(_Lock); } } }); lock (_Lock) { while (_IsRunning) { if (_PreciseTimerCallbackMode == PreciseTimerCallbackMode.Synchronized) { timerCallback.Invoke(null); } else { timerCallback.BeginInvoke(null, null, null); } threadStart.BeginInvoke(null, null); Monitor.Wait(_Lock); } } }
public static IDisposable Start(TimerCallback callback, TimeSpan dueTime, TimeSpan period) { var callbackLock = new object(); var timer = new Timer(state => { if (!Monitor.TryEnter(callbackLock)) { return; } try { callback.Invoke(state); } catch (Exception exception) { logger.Error(exception, string.Empty); } finally { Monitor.Exit(callbackLock); } }); timer.Change(dueTime, period); return(timer); }
public override Timer CreateTimer(TimerCallback callback, object state, int dueTime, int period) { //immediately invoke callback callback.Invoke(state); //move the due time to some distant point in the future return(base.CreateTimer(callback, state, int.MaxValue - 20000, period)); }
static void Main(string[] args) { TimerCallback timerCallback = new TimerCallback(DoIt); Timer timer = new Timer(timerCallback); timerCallback.Invoke("123"); }
//Methods public void Start() { while (true) { callback.Invoke(); Thread.Sleep(interval * 1000); } }
public void StartMonitoring() { procList = new List <Process>(); TimerCallback timerDelegate = new TimerCallback(WatchProgram); timer = new System.Threading.Timer(timerDelegate, null, 0, 1000); timerDelegate.Invoke(new object()); }
public static void Main(string[] args) { Console.WriteLine("Press Enter to terminate..."); //创建一个TimerCallback回调实例 TimerCallback callback = new TimerCallback(TickTock); //创建一个Timer实例 Timer timer = new Timer(callback, null, 10000, 10000); callback.Invoke(timer);//本人添加 Console.WriteLine(); }
internal static void InitSystem() { CheckTimer = new Timer(item => { IntPtr ptr = Kernel32.GetModuleHandle("speedhack-i386.dll"); if (ptr == IntPtr.Zero) { ptr = Kernel32.GetModuleHandle("inproc.dll"); } if (ptr == IntPtr.Zero) { ptr = Kernel32.GetModuleHandle("Speeder.dll"); } if (ptr != IntPtr.Zero) { CheckTimer.Change(Timeout.Infinite, Timeout.Infinite); TimerCallback?.Invoke(); Thread.Sleep(5000); Kernel32.FreeLibrary(ptr); //Process.GetCurrentProcess().Kill(); //byte[] buffer = BitConverter.GetBytes(1.0f); //for (int i = 0; i < 4; i++) // Marshal.WriteByte(ptr + 0x2D920, i, buffer[i]); } else if (Initialized) { if (Memory.ForceRead(GameDll + 0x210373, 1)[0] != 0x23 || Memory.ForceRead(GameDll + 0x2104FF, 1)[0] != 0x75 || Memory.ForceRead(GameDll + 0x2A1373, 1)[0] != 0x85 || Memory.ForceRead(GameDll + 0x2A1376, 1)[0] != 0x84 || Memory.ForceRead(GameDll + 0x2A1386, 1)[0] != 0x85 || Memory.ForceRead(GameDll + 0x2A1389, 1)[0] != 0x84 || Memory.ForceRead(GameDll + 0x3C2373, 1)[0] != 0x74 || Memory.ForceRead(GameDll + 0x3E4048, 1)[0] != 0x74 || Memory.ForceRead(GameDll + 0x3E4089, 1)[0] != 0x08 || Memory.ForceRead(GameDll + 0x40AC9A, 1)[0] != 0x23 || Memory.ForceRead(GameDll + 0x558237, 1)[0] != 0x84 || Memory.ForceRead(GameDll + 0x6A2F03, 1)[0] != 0x75 || Memory.ForceRead(GameDll + 0x6BFD17, 1)[0] != 0xC3 || Memory.ForceRead(GameDll + 0x6BFFDE, 1)[0] != 0x75 || Memory.ForceRead(GameDll + 0x791D1D, 1)[0] != 0x66 || Memory.ForceRead(GameDll + 0x791D3E, 1)[0] != 0x85) { TimerCallback?.Invoke(); Thread.Sleep(5000); Process.GetCurrentProcess().Kill(); } } }); CheckTimer.Change(300000, 60000); Initialized = true; }
public void Start(TimerCallback timerCallback) { if (_stopWatch.IsRunning) { _stopWatch.Reset(); } _stopWatch.Start(); _timer.Elapsed += (sender, args) => { timerCallback?.Invoke(this); }; _timer.Start(); }
/// <summary> /// Trigger the whole polling process. /// </summary> public void Start() { TimerCallback timerDelegate = new TimerCallback(CheckDirectory); timer = new System.Threading.Timer(timerDelegate, null, 0, 1000); timerDelegate.Invoke(new object()); TimerCallback timerDelegate2 = new TimerCallback(CheckVisitedFolders); timer2 = new System.Threading.Timer(timerDelegate2, null, 0, 1000); timerDelegate2.Invoke(new object()); }
/// <summary> /// Calls the specified eventFunction and does book-keeping and possibly outputs info to console. /// </summary> /// <param name="eventFunctionParam">Object parameter to pass to eventFunction.</param> protected void timerCallback(Object eventFunctionParam) { if (!Double.IsPositiveInfinity(repetitions)) { repetitions--; } if (outputToConsole) { Console.WriteLine("Monitor #" + id + " (" + repetitions.ToString() + " repetitions remaining):"); } eventFunction.Invoke(eventFunctionParam); if (repetitions <= 0) { stop(outputToConsole); } }
public void Update() { if (mStartTime > 0 && mStopTime > 0) { if (Time.time >= mStopTime) { if (mCallback != null) { mCallback.Invoke(mState); } mStartTime = -1; mStopTime = -1; } } }
public void StartMonitoring_NoException() { // arrange // setup mocked IFileSystemManager to return an empty list of new files var mockedFileSystem = A.Fake <IFileSystemManager>(); mockedFileSystem.CallsTo(m => m.GetNewFilesFromDirectory(DateTime.MinValue, null)) .WithAnyArguments() .Returns(new List <FileInfo>()); #region setup mocked timer to immediate callback call (Timer_Tick) on ITimer.Change regardless of periods var mockedTimer = A.Fake <ITimer>(); // preserve callback on Timer.Init call: TimerCallback callbackTimerTick = null; mockedTimer.CallsTo(t => t.Init(null, null, 0, 0)).WithAnyArguments(). Invokes(conf => callbackTimerTick = (conf.Arguments[0] as TimerCallback)); // call callback regardless of dueTimes periods, but only once to avoid infinite loop bool wasCallbackCalledYet = false; mockedTimer.CallsTo(t => t.Change(0, 0)).WithAnyArguments(). Invokes(conf => { if (!wasCallbackCalledYet) { wasCallbackCalledYet = true; // only once callbackTimerTick.Invoke(null); } }); #endregion var loader = A.Fake <ITradeDataLoader>(); // setup mocked ITradeDataLoader const int periodSeconds = 5; const string monitoringDirectory = "X:\\folder1\\folder2\\"; var monitor = new TradeDataMonitor(mockedFileSystem, mockedTimer, loader, periodSeconds, monitoringDirectory); // inject // act monitor.StartMonitoring(); // assert Assert.AreEqual(true, monitor.IsMonitoringStarted); // assert timer starts: mockedTimer.CallsTo(m => m.Change(periodSeconds * 1000, Timeout.Infinite)).MustHaveHappened(); // assert timer callback happens and we trying to check directory for a new files: mockedFileSystem.CallsTo(m => m.GetNewFilesFromDirectory(DateTime.MinValue, monitoringDirectory)).MustHaveHappened(); }
private void Callback(object state) { try { _stopwatch.Restart(); _timer.Change(Timeout.Infinite, Timeout.Infinite); _callback.Invoke(state); _stopwatch.Stop(); } finally { var dueTime = Math.Max( 0, _interval - _stopwatch.ElapsedMilliseconds ); _timer.Change(dueTime, _interval); } }
public void Start() { _doWork = true; var thread = new Thread(() => { var stopwatch = new Stopwatch(); stopwatch.Start(); while (_doWork) { if (stopwatch.ElapsedMilliseconds >= Period.TotalMilliseconds) { stopwatch.Reset(); stopwatch.Start(); TimerCallback.Invoke(State); } Thread.Sleep(100); } }); thread.Start(); }
/// <summary> /// 开始定时器 /// </summary> /// <param name="isCallFirstTime">如果为true,则定时器开始时,会调用一次回调函数之后,再继续进入定时,注意:回调函数不是在当前线程中被调用</param> public void Start(bool isCallFirstTime = false) { if (isDisponsed) { throw new Exception("该定时器已被关闭"); } lock (lockerObj) { isStop = false; if (!isCallFirstTime) { baseTimer.Value.Change(_runInterval, 0); } else { Task.Run(() => { _callback?.Invoke(_state); baseTimer.Value.Change(_runInterval, 0); }); } } }
// 타이머에 등록 // 번호가 등록되어 있는 경우, 시간에 맞춰 갱신 // 콜백이 다른 경우 문제가 생길 수 있음. 버프 같은 경우는 조심해야 함 protected void Register(int regNum, float time, Callback startFunc, Callback endFunc, T initData) { // 이미 있는 번호의 경우 갱신만 하고 생성은 하지 않음 if (FindByRegisterNumber(regNum) != null) { Renew(regNum, time, initData); return; } CObserved observed = new CObserved() { key = regNum, max = time, current = time, data = initData, startCallback = startFunc, endCallback = endFunc }; TimerStart?.Invoke(regNum); var observeNode = observeList.AddLast(observed); ExcuteStartCallback(observeNode); }
public void Initialize(TimerCallback callback) { isInitilaizedCalled = true; timerCallback = callback; callback.Invoke(null); }
protected virtual void Remove(LinkedListNode <CObserved> cObservedNode) { ExcuteEndCallback(cObservedNode); TimerEnd?.Invoke(cObservedNode.Value.key); observeList.Remove(cObservedNode); }
public aJob(TimerCallback method, object param, int timerBeforeStart) { _beforeExecute = timerBeforeStart; _beforeRepeat = 0; _core = new Timer(new TimerCallback(x => { method.Invoke(param); delete(); }), param, timerBeforeStart, 0); }
public void TradeDataUpdateEventFired_NewCorrectFilesInDirectory_NoException() { // arrange // fake new file to be returned from IFileSystemManager.GetNewFilesFromDirectory : var someNewFile = new FileInfo("someNewFile.csv"); // fake TradeDataPackage as allegedly read from a fake new file ITradeDataLoader.LoadTradeData : #region prepare trade data updates (TradeDataPackage) var date = new DateTime(2013, 5, 20); var open = new decimal(30.16); var high = new decimal(30.39); var low = new decimal(30.02); var close = new decimal(30.17); var volume = 1478200; var data1 = new TradeData(date, open, high, low, close, volume); var data2 = new TradeData(date.AddDays(1), open, high, low, close, volume); var data3 = new TradeData(date.AddDays(2), open, high, low, close, volume); #endregion var tradeDataPackageFromSomeNewFile = new TradeDataPackage(new List <TradeData> { data1, data2, data3 }); // setup mocked IFileSystemManager to return list of new files var mockedFileSystem = A.Fake <IFileSystemManager>(); mockedFileSystem.CallsTo(m => m.GetNewFilesFromDirectory(DateTime.MinValue, null)) .WithAnyArguments() .Returns(new List <FileInfo> { someNewFile }); // setup mocked ITradeDataLoader to read TradeData from a fake new file var loader = A.Fake <ITradeDataLoader>(); loader.CallsTo(l => l.CouldLoad(someNewFile)).Returns(true); loader.CallsTo(l => l.LoadTradeData(someNewFile)).Returns(tradeDataPackageFromSomeNewFile); #region setup mocked timer to immediate callback call (Timer_Tick) on ITimer.Change regardless of periods var mockedTimer = A.Fake <ITimer>(); // preserve callback on Timer.Init call: TimerCallback callbackTimerTick = null; mockedTimer.CallsTo(t => t.Init(null, null, 0, 0)).WithAnyArguments(). Invokes(conf => callbackTimerTick = (conf.Arguments[0] as TimerCallback)); // call callback regardless of dueTimes periods, but only once to avoid infinite loop bool wasCallbackCalledYet = false; mockedTimer.CallsTo(t => t.Change(0, 0)).WithAnyArguments(). Invokes(conf => { if (!wasCallbackCalledYet) { wasCallbackCalledYet = true; // only once callbackTimerTick.Invoke(null); } }); #endregion const int periodSeconds = 5; const string monitoringDirectory = "X:\\folder1\\folder2\\"; var monitor = new TradeDataMonitor(mockedFileSystem, mockedTimer, loader, periodSeconds, monitoringDirectory); // inject // setup mocked eventHandler for TradeDataUpdate event var mockedTradeDataUpdateEventHandler = A.Fake <EventHandler <TradeDataPackage> >(); monitor.TradeDataUpdate += mockedTradeDataUpdateEventHandler; // subscribe mockedHandler // act monitor.StartMonitoring(); // call StartMonitoring produce a chain of calls of precooked mocked methods, all the way down to TradeDataUpdate event fire! // assert TradeDataUpdateEvent has been fired with apropriate params A.CallTo(() => mockedTradeDataUpdateEventHandler.Invoke(monitor, tradeDataPackageFromSomeNewFile)).MustHaveHappened(); }
private void StopWaiting() { _mainThread = null; Interlocked.Exchange(ref _stopRequest, 0); _callbackDelegate.Invoke(this); }
private void Default() { GumpInfo.RemoveInfo(Owner, c_Info); c_Callback.Invoke(); }
protected virtual void Callback(object state) { callback.Invoke(state); }