Example #1
0
        static void Main(string[] args)
        {
            System.Console.WriteLine("Enter timer time");
            int tick;

            try
            {
                tick = int.Parse(System.Console.ReadLine());
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.Message);
                tick = 1000;
            }
            FirstListener  first  = new FirstListener();
            SecondListener second = new SecondListener();
            EventTimer     timer  = new EventTimer(tick);

            timer.Register(Listener);
            first.Register(timer);
            second.Register(timer);
            try
            {
                timer.Start();
            }
            catch (AggregateException e)
            {
                foreach (var innerException in e.InnerExceptions)
                {
                    System.Console.WriteLine(innerException.Message);
                }
            }
            System.Console.ReadLine();
        }
Example #2
0
        public EPollEventModule(int maxEvents = 256)
        {
            Contract.Requires(maxEvents > 0);

            _epoll = new EPollQueue(maxEvents);
            Timer  = new EventTimer();
        }
        private async Task <Document> GetExternalDocumentAsync(DocumentId documentId)
        {
            // build the request URI
            var builder = new UriBuilder(documentId.TypeId);
            NameValueCollection queryString = HttpUtility.ParseQueryString(builder.Query);

            queryString["apiKey"] = _key;
            builder.Query         = queryString.ToString();
            string requestUri = builder.ToString();

            // make the HTTP request
            HttpResponseMessage response = null;

            byte[]   content  = null;
            TimeSpan duration = await EventTimer.TimeAsync(async() =>
            {
                response = await _httpClient.GetAsync(requestUri);
                content  = await response.Content.ReadAsByteArrayAsync();
            });

            _eventSource.OnFetchedDocumentFromRottenTomatoesApi(documentId, response.StatusCode, content.LongLength, duration);

            response.EnsureSuccessStatusCode();

            return(new Document
            {
                Id = documentId,
                Content = content
            });
        }
Example #4
0
    // Called by the BattleManager when an enemy reaches 0 hp.
    public void StartSpawn(Vector2 origPos, Vector2 targetPos, int reward, bool isBoss)
    {
        // Add timer to scene
        spawnTimer = gameObject.AddComponent <EventTimer>();

        // Timer triggers SpawnCoin method
        spawnTimer.AddListener_Finished(SpawnCoin);

        // Store prefab for instantiating
        prefabCoinSpawn = Resources.Load <GameObject>(@"BattlePrefabs\CoinSpawn");

        // Set positions
        spawnPos = origPos;
        bankPos  = targetPos;

        valueRemaining = reward;

        // generate an interval between 0.14 and 0.01 based on the value
        // bigger cash rewards have shorter intervals, so that a flurry of coins are produced
        spawnInterval = Mathf.Clamp(0.14f / (float)Math.Pow(2d, Math.Log10(valueRemaining) - 1d), 0.01f, 0.14f);

        // Total spawn duration is longer for a boss, due to the longer death sequence
        float duration = isBoss ? SpawnDuration_Boss : SpawnDuration;

        // Calculate the value of each coin, given a total value, an interval, and a duration
        goldPerSpawn = Mathf.Max(
            Mathf.CeilToInt(valueRemaining / (duration / spawnInterval)), 7);

        // Set the interval on the timer
        spawnTimer.Duration = spawnInterval;

        // Spawn the first coin
        SpawnCoin();
    }
Example #5
0
        public async Task <IEnumerable <T> > ListAsync(string partitionKey, string rowKeyLowerBound, string rowKeyUpperBound)
        {
            string condition = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey);

            if (rowKeyLowerBound != null)
            {
                condition = TableQuery.CombineFilters(
                    condition,
                    TableOperators.And,
                    TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.GreaterThanOrEqual, rowKeyLowerBound));
            }

            if (rowKeyUpperBound != null)
            {
                condition = TableQuery.CombineFilters(
                    condition,
                    TableOperators.And,
                    TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.LessThanOrEqual, rowKeyUpperBound));
            }

            TableQuery <GenericTableEntity <T> > query = new TableQuery <GenericTableEntity <T> >().Where(condition);

            TableQuerySegment <GenericTableEntity <T> > result = null;
            TimeSpan duration = await EventTimer.TimeAsync(async() =>
            {
                result = await _cloudTable.ExecuteQuerySegmentedAsync(query, null);
            });

            _eventSource.OnFetchedListFromAzure(partitionKey, result.Results.Count, duration);

            return(result.Results.Select(r => r.Content));
        }
Example #6
0
        public MainWindow()
        {
            InitializeComponent();

            // Regist to System time change event
            SystemEvents.TimeChanged += OnTimeChangeEvent;

            double TimeOfExecution = 5; // 0500

            DateTime now      = DateTime.Now;
            DateTime today5am = now.Date.AddHours(TimeOfExecution);

            today5am = today5am.AddMinutes(25);
            Debug.WriteLine(today5am.ToString());
            DateTime next5am = now <= today5am ? today5am : today5am.AddDays(1);
            DateTime nextNow = now.Date.AddSeconds(5);

            // nextNow - DateTime.Now
            // this.testTimer = new System.Threading.Timer(new TimerCallback(this.OnRestartCallback), null, nextNow.Subtract(now.Date), TimeSpan.FromSeconds(15));

            // this.testDispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            // this.testDispatcherTimer.Tick += new EventHandler(OnRestartCallback);
            // this.testDispatcherTimer.Interval = nextNow.Subtract(now.Date);
            // this.testDispatcherTimer.Start();

            m_myTimer = new EventTimer(new EventHandler(OnRestartCallback), nextNow, TimeSpan.FromSeconds(10));
        }
Example #7
0
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            if (disposing)
            {
                if (EventTimer != null)
                {
                    EventTimer.Stop();
                    EventTimer.Enabled  = false;
                    EventTimer.Elapsed -= ElapsedEventTick;

                    EventTimer.Dispose();
                    EventTimer = null;
                }

                if (SongTimer != null)
                {
                    SongTimer.Stop();
                    SongTimer.Enabled  = false;
                    SongTimer.Elapsed -= ElapsedSongTick;

                    SongTimer.Dispose();
                    SongTimer = null;
                }
            }

            _disposed = true;
        }
Example #8
0
        // 计时器完成 不包含中途退出的情况
        private void OnTimerFinish(EventTimer timer)
        {
            IModelData target = timer.Parameters[0] as IModelData;

            DoExit(target);
            DoRoute(target, ERuleKey.RouteFinish);
        }
Example #9
0
    // Trigger all registered callbacks.
    public virtual void OnPointerClick(PointerEventData eventData)
    {
        if (eventData.button != PointerEventData.InputButton.Left)
        {
            return;
        }

        pointerEventData = eventData;

        {
            EventTimer.AddTimer(delayInvokeTime, Press, null, false);
        }

        // lock
        Lock(true);
        switch (type)
        {
        case ButtonType.Once:
        {
            EventTimer.AddTimer(autoLockOnceTime, Unlock, null, false);
        }
        break;

        case ButtonType.Repeat:
        {
            EventTimer.AddTimer(autoLockRepeatTime, Unlock, null, false);
        }
        break;
        }

        // Play sound
        PlaySound();
    }
Example #10
0
    // Start is called before the first frame update
    private void Start()
    {
        // Make the menu capable of invoking the end of a turn
        turnInvoker = gameObject.AddComponent <TurnInvoker>();

        EventManager.AddListener_Battle_InvSelect(MakeSelection);

        // for displaying "You are at full."
        messageTimer          = gameObject.AddComponent <EventTimer>();
        messageTimer.Duration = messageTimerDuration;
        messageTimer.AddListener_Finished(ResetMessage);

        // show gold
        goldText.text = BattleLoader.Party.Gold.ToString();
        // cannot use until a selection is made
        useButton.GetComponent <Button>().interactable = false;

        // retrieve inventory from HeroParty
        partyStash = BattleLoader.Party.Inventory;

        messageText.text = "";

        // Only used for invoking disable. No button.
        uiEnabler = gameObject.AddComponent <UIEnabler>();

        PopulateGrid();
    }
Example #11
0
 public EventTimerInst(EventTimer timer, EventFunction eventFunc, CharacterPawn pawn, ActorInstance.ActorBase actor)
 {
     this.timer         = timer;
     this.funcToExecute = eventFunc;
     this.pawn          = pawn;
     this.actor         = actor;
     timer.Init(this);
 }
Example #12
0
 // Use this for initialization
 void Start()
 {
     m_sineOffset = 0.0f;
     if (eventTimer == null)
     {
         eventTimer = FindObjectOfType <EventTimer>();
     }
 }
Example #13
0
        protected override void OnExecute(IModelData target)
        {
            int        triggerCount = ToolParser.IntParse(Attributes[ERuleKey.TriggerCount]);
            float      timerTime    = ToolParser.FloatParse(Attributes[ERuleKey.TimerTime]);
            EventTimer timer        = target.RegisterTimer(timerTime, new object[] { target }, OnTimerFinish, triggerCount, OnTimerTrigger);

            TimerDic.Add(this, timer);
        }
Example #14
0
        public void EventTimer_xTime_RaiseTimerOccuredEventNotOccuredBeforexTime(int time)
        {
            _uut = new EventTimer(_evnt, time);
            _uut.RaiseTimerOccuredEvent += _sub.EventSub;

            System.Threading.Thread.Sleep(time - _margin);
            Assert.That(_sub.Cnt, Is.EqualTo(0));
        }
Example #15
0
        /// <summary>
        /// 注册一个定时器
        /// </summary>
        /// <param name="time">定时器时长</param>
        /// <param name="parameters">参数</param>
        /// <param name="callback">回调</param>
        /// <param name="isInvoked">是否invoke</param>
        /// <returns>定时器</returns>
        public EventTimer RegisterTimer(float time, object[] parameters, EventTimer.OnTimerFinishCallback onTimerFinishCallback, int triggerTime = 0, Action <EventTimer> callback = null)
        {
            EventTimer timer = new EventTimer(time, parameters, onTimerFinishCallback, triggerTime, callback);

            mTimerList.Add(timer);

            timer.RegisterTimerFinish(OnTimerFinished);
            return(timer);
        }
Example #16
0
        public void StartEventTimer()
        {
            if (EventTimer == null || EventTimer.Interval <= -1)
            {
                return;
            }

            EventTimer.Start();
        }
Example #17
0
    public void UnRigisterTimer(EventTimer timer)
    {
        if (!mTimerSet.Remove(timer))
        {
            return;
        }

        CTimerManager.Instance.UnRegisterTimer(timer);
    }
Example #18
0
        public void EventTimer_xTime_RaiseTimerOccuredEventAfterxTime(int time)
        {
            _uut = new EventTimer(_evnt, time);
            _uut.RaiseTimerOccuredEvent += _sub.EventSub;

            System.Threading.Thread.Sleep(time + _margin); //Adds a little bit to ensure that the timer has time to call the event

            Assert.That(_sub.Cnt, Is.EqualTo(1));
        }
Example #19
0
        public async Task DeleteMessageAsync(QueueMessage <T> queueMessage)
        {
            TimeSpan duration = await EventTimer.TimeAsync(async() =>
            {
                await _cloudQueue.DeleteMessageAsync(queueMessage.Id, queueMessage.PopReceipt);
            });

            _eventSource.OnQueueMessageDeleted(duration);
        }
Example #20
0
 /* Disposes resources */
 protected override void Dispose(bool disposing)
 {
     if (disposing && (components != null))
     {
         EventTimer.Stop();
         EventTimer.Dispose();
         components.Dispose();
     }
     base.Dispose(disposing);
 }
Example #21
0
        public async Task SetAsync(string key, byte[] value)
        {
            CloudBlockBlob cloudBlockBlob = _blobContainer.GetBlockBlobReference(key);
            TimeSpan       duration       = await EventTimer.TimeAsync(async() =>
            {
                await cloudBlockBlob.UploadFromByteArrayAsync(value, 0, value.Length);
            });

            _eventSource.OnBlobUploadedToAzure(key, value.LongLength, duration);
        }
Example #22
0
    // additional sprites defined by child classes of HeroSprites

    #endregion

    #region Methods

    // Initializes this instance of HeroSprites
    // used by BattleHero.LoadObj in BattleManager
    // also used by HeroMovement
    public void SetObj(GameObject heroObj, BattleHero hero = null)
    {
        this.hero          = hero;
        heroObject         = heroObj;
        heroSprite         = heroObj.GetComponent <Sprite>();
        heroSpriteRenderer = heroObj.GetComponent <SpriteRenderer>();

        spriteTimer = heroObj.AddComponent <EventTimer>();
        spriteTimer.AddListener_Finished(ReturnToIdleSprite);
    }
Example #23
0
        public async void ElapsedEventTick(object sender, ElapsedEventArgs e)
        {
            SpotifyLatestStatus = await SpotifyProcess.GetSpotifyStatus();

            if (SpotifyLatestStatus?.CurrentTrack == null)
            {
                EventTimer.Start();
                return;
            }

            var newestTrack = SpotifyLatestStatus.CurrentTrack;

            if (Track != null)
            {
                if (newestTrack.Playing != Track.Playing)
                {
                    if (newestTrack.Playing)
                    {
                        SongTimer.Start();
                    }
                    else
                    {
                        SongTimer.Stop();
                    }

                    await Task.Run(() => OnPlayStateChange?.Invoke(this, new PlayStateEventArgs()
                    {
                        Playing = newestTrack.Playing
                    }));
                }
                if (!newestTrack.Equals(Track))
                {
                    SongTimer.Start();
                    await Task.Run(async() => OnTrackChange?.Invoke(this, new TrackChangeEventArgs()
                    {
                        OldTrack = Track,
                        NewTrack = await SpotifyLatestStatus.GetTrack()
                    }));
                }
                if (Track.CurrentPosition != null || newestTrack != null)
                {
                    await Task.Run(() => OnTrackTimeChange?.Invoke(this, new TrackTimeChangeEventArgs()
                    {
                        TrackTime = newestTrack.Equals(Track) ? Track?.CurrentPosition ?? 0 : 0
                    }));
                }
            }
            if (newestTrack != null)
            {
                newestTrack.CurrentPosition = newestTrack.Equals(Track) ? Track?.CurrentPosition ?? 0 : (int?)null;
                Track = newestTrack;
            }
            EventTimer.Start();
        }
Example #24
0
        public async Task <QueueMessage <T> > GetMessageAsync()
        {
            CloudQueueMessage cloudQueueMessage = null;
            TimeSpan          duration          = await EventTimer.TimeAsync(async() =>
            {
                cloudQueueMessage = await _cloudQueue.GetMessageAsync();
            });

            _eventSource.OnQueueMessageFetched(duration);
            return(Deserialize(cloudQueueMessage));
        }
Example #25
0
        /// <summary>
        /// Removes a timer from the EventTimer database by its <paramref name="TimerTracker"/> token.
        /// </summary>
        /// <remarks>This function removes the timer given by its <paramref name="TimerTracker"/> from the database completely.</remarks>
        /// <param name="TimerTracker">The unique identifier of the target EventTimer.</param>

        public void RemoveTimer(string TimerTracker)
        {
            EventTimer Timer = EventTimersDB.EventTimers.Find(TimerTracker);

            if (Timer != null)
            {
                EventTimersDB.EventTimers.Remove(Timer);
            }

            EventTimersDB.SaveChanges();
        }
Example #26
0
        public override async void Initialize()
        {
            EventTimer Timer = TimerService.EventTimersDB.EventTimers.AsQueryable().Where(Timer => Timer.CallbackClass.Equals(GetType().Name)).FirstOrDefault();

            if (Timer != null)
            {
                TimerService.EventTimersDB.EventTimers.Remove(Timer);
            }

            await CreateEventTimer(AddLevels, new(), LevelingConfiguration.XPIncrementTime, TimerType.Interval);
        }
Example #27
0
        public async Task <bool> ExistsAsync(string key)
        {
            CloudBlockBlob cloudBlockBlob = _blobContainer.GetBlockBlobReference(key);
            bool           exists         = false;
            TimeSpan       duration       = await EventTimer.TimeAsync(async() =>
            {
                exists = await cloudBlockBlob.ExistsAsync();
            });

            _eventSource.OnBlobExistenceCheckedInAzure(key, exists, duration);
            return(exists);
        }
Example #28
0
    EventTimer boltDeathTimer; // timer between impact and destroy()

    // Start is run before the GameObject's first frame update
    protected override void Start()
    {
        base.Start();

        // load halfBolt sprite
        halfBolt = Resources.Load <Sprite>(@"Sprites\Hero\EdgarBolt1");

        // set up timer
        boltDeathTimer          = gameObject.AddComponent <EventTimer>();
        boltDeathTimer.Duration = 1.5f;
        boltDeathTimer.AddListener_Finished(DestroyBolt);
    }
Example #29
0
        /// <summary>
        /// Create a Screen Transition
        /// </summary>
        /// <param name="tilesX">Horizontal Tile Count</param>
        /// <param name="tilesY">Vertical Tile Count</param>
        /// <param name="reverseTransition">Bool to specify whether to reverse the transition or not</param>
        /// <param name="transitionTime">Time to complete transition</param>
        public ScreenTransition(int tilesX, int tilesY, bool reverseTransition, double transitionTime)
        {
            tileCount = new Vector2(tilesX, tilesY);
            tileSize = new Vector2(GlobalGameData.windowWidth / tileCount.X, GlobalGameData.windowHeight / tileCount.Y);

            reverse = reverseTransition;

            timer = new EventTimer(0, transitionTime);
            timer.OnEnd += TransitionEnd;

            args = EventArgs.Empty;
        }
Example #30
0
    public EventTimer RegisterTimer(float time, object[] parameters, EventTimer.OnTimerFinishCallback onTimerFinishCallback, int triggerTime = 0, Action <EventTimer> callback = null)
    {
        callback += OnTimer;
        EventTimer timer = CTimerManager.Instance.RegisterTimer(time, parameters, onTimerFinishCallback, triggerTime, callback);

        if (null == mTimerSet)
        {
            mTimerSet = new HashSet <EventTimer>();
        }

        mTimerSet.Add(timer);
        return(timer);
    }
Example #31
0
    // Start is run before the first frame update
    private void Start()
    {
        // Listen for user selections of panels
        EventManager.AddListener_Inventory_Select(MakeSelection);

        // Set up message timer
        messageTimer          = gameObject.AddComponent <EventTimer>();
        messageTimer.Duration = messageTimerDuration;
        messageTimer.AddListener_Finished(ResetMessage);

        // Display current gold
        goldText.text = BattleLoader.Party.Gold.ToString();
    }
Example #32
0
 private void SetTimerEvent(EventTimer timerEvent, int timerTimeTick)
 {
     if (timerBlock!=null)
         timerBlock.Stop();
     timerBlock = new System.Timers.Timer(timerTimeTick);
     timerBlock.Elapsed += new System.Timers.ElapsedEventHandler(timerEvent);
     timerBlock.AutoReset = true;
     timerBlock.Start();
 }
Example #33
0
        /// <summary>
        /// Reset the level
        /// </summary>
        /// <param name="playerCount">Number of players</param>
        /// <param name="p1ControlType">Control type index for player 1</param>
        /// <param name="p2ControlType">Control type index for player 2</param>
        /// <param name="p3ControlType">Control type index for player 3</param>
        /// <param name="p4ControlType">Control type index for player 4</param>
        public void Reset(int playerCount, int p1ControlType, int p2ControlType, int p3ControlType, int p4ControlType)
        {
            this.playerCount = playerCount;

            tileObjectManager.Reset();
            fireManager.Reset();

            //Reset players to positions
            players[0].Reset(1, 1);
            players[1].Reset(GlobalGameData.gridSizeX - 2, 1);
            players[2].Reset(1, GlobalGameData.gridSizeY - 2);
            players[3].Reset(GlobalGameData.gridSizeX - 2, GlobalGameData.gridSizeY - 2);

            SetPlayerControlIdentifiers(playerCount, p1ControlType, p2ControlType, p3ControlType, p4ControlType);

            gameOver = false;

            checkWinState = new EventTimer(0, 1, true);
            checkWinState.OnEnd += checkIfWinOrTie;
        }