Search code examples
c#timerscheduled-taskstaskscheduler

TaskScheduler vs Timer for scheduling tasks in C#: When to use?


Recently I am studying and trying C# and I have some confusing points to clear out regarding tasks scheduling in C#.

According to what I learnt, I have understood that task scheduling in C# can be done by using Timer and TaskScheduler.

I have followed these articles: create task scheduler using TaskScheduler class, create task scheduler using Timers

So my confusion is when should we actually use Timer and TaskScheduler for scheduling tasks?

Thank you!


Solution

  • Forget about the TaskScheduler class in C#, it's to do with the way tasks are scheduled on the thread-pool, though not to be confused with the Windows Task Scheduler, which runs code on Windows operating system and is agnostic to the language it's written in.

    So what you have left are

    1. Timers (which are not really suited for accurate scheduling over long periods of time).
    2. Tasks with delays (which take a lot of work to create actual schedules accurately).
    3. Other fancy things like Reactive Extensions (similar to the above).
    4. job scheduling frameworks (like quartz.net) which give you all the tools you need to schedule tasks to run once or regularly in any time frame and any type of schedule you wish in C#.

    For beginners, Timers are probably where you want to be.