Timers to use various Task(s)

Posted on

Problem

I am developing a C# program, which performs various tasks in parallel threads. I created a Base task and let all tasks derived from this class execute. I just want to know if this a viable approach which won’t cause unforeseen consequences if various tasks run in conjunction.

public abstract class BaseTask
{
     private readonly Timer _taskTimer = new Timer();

    // Derived classes to define thier own time Intervals
    protected abstract double TimerInterval { get; set; }

    public void Start()
    {
        // Set default Timer -- 10 seconds
        TimerInterval = 10000;

        _taskTimer.AutoReset = true;
        _taskTimer.Interval = TimerInterval;
        _taskTimer.Elapsed += ExecuteTask;
        _taskTimer.Start();
    }

    public void Stop()
    {
        _taskTimer.Stop();
    }

    public abstract void ExecuteTask(object sender, ElapsedEventArgs e);
}


// Derived Task Class
 class DerivedTask : BaseTask
 {
   protected override double TimerInterval
    {
        get { return 5000; }
        set {  }
    }

    public override void ExecuteTask(object sender, ElapsedEventArgs e)
    {
        // Do My Derived task operations here
    }
 }

 // Now In Main..
 static void Main()
 {
    DerivedTask dTask = new DerivedTask ();
    _dTask .Start();
 }

Solution

I don’t see any reason to use Base and Derived classes in your case. At least with the context you’ve provided.

public class TimerTask
{
    private readonly Timer _taskTimer;

    public TimerTask(Action action, int interval = 10000)
    {
        _taskTimer = new Timer { AutoReset = true, Interval = interval };
        _taskTimer.Elapsed += (_, __) => action();
    }

    public void Start() { _taskTimer.Start(); }

    public void Stop() { _taskTimer.Stop(); }
}

Usage:

void Main()
{
    var t1 = new TimerTask(() => Console.WriteLine("t1"), 100);
    t1.Start();
    Thread.Sleep(1000);
    t1.Stop();
}

System.Timers.Timer is thread-safe, but you have to make sure that your code is thread-safe.

Leave a Reply

Your email address will not be published. Required fields are marked *