Howto C# Timer ?

DreTaX

Probably knows the answer...
Administrator
Jun 29, 2014
4,095
4,815
113
At your house.
github.com
Here is the timer class: (Put it in a separate class file)

C#:
namespace Test
{
    using System;
    using System.Collections.Generic;
    using System.Timers;

    public class TestTimedEvent {

        private Dictionary<string, object> _args;
        private readonly System.Timers.Timer _timer;
        private long lastTick;
        private int _elapsedCount;

        public delegate void TimedEventFireDelegate(TestTimedEvent evt);

        public event TimedEventFireDelegate OnFire;

        public TestTimedEvent(double interval) {
            this._timer = new System.Timers.Timer();
            this._timer.Interval = interval;
            this._timer.Elapsed += new ElapsedEventHandler(this._timer_Elapsed);
            this._elapsedCount = 0;
        }

        public TestTimedEvent(double interval, Dictionary<string, object> args)
            : this(interval) {
            this.Args = args;
        }

        private void _timer_Elapsed(object sender, ElapsedEventArgs e) {
            if (this.OnFire != null) {
                this.OnFire(this);
            }

            this._elapsedCount += 1;
            this.lastTick = DateTime.UtcNow.Ticks;
        }

        public void Start() {
            this._timer.Start();
            this.lastTick = DateTime.UtcNow.Ticks;
        }

        public void Stop() {
            this._timer.Stop();
        }

        public void Kill() {
            this._timer.Stop();
            this._timer.Dispose();
        }

        public Dictionary<string, object> Args {
            get { return this._args; }
            set { this._args = value; }
        }

        public double Interval {
            get { return this._timer.Interval; }
            set { this._timer.Interval = value; }
        }

        public double TimeLeft {
            get { return (this.Interval - ((DateTime.UtcNow.Ticks - this.lastTick) / 0x2710L)); }
        }

        public int ElapsedCount {
            get { return this._elapsedCount; }
        }
    }
}
Here are the callback and the create methods that you place in the plugin's class:

C#:
public TestTimedEvent CreateParallelTimer(int timeoutDelay, Dictionary<string, object> args)
{
            TestTimedEvent timedEvent = new TestTimedEvent(timeoutDelay);
            timedEvent.Args = args;
            timedEvent.OnFire += Callback;
            return timedEvent;
}

public void Callback(TestTimedEvent e)
{
            Dictionary<string, object> data = e.Args;
            e.Kill();
}
Example:

C#:
Dictionary<string, object> d = new Dictionary<string, object>();
d["Player"] = p;
d["Position"] = p.Location;
CreateParallelTimer(2000, d).Start();
 
Last edited: