---
title: "Reactive Extensions (Rx) - Part 4 - Replacing Timers - Muhammad Rehan Saeed"
description: "You should definitely consider using Reactive Extensions (Rx) is as a direct replacement for .NET Timers. This post will explain how."
canonical_url: "https://rehansaeed.com/reactive-extensions-part4-replacing-timers/"
last_updated: "2014-03-11T00:00:00+00:00"
meta:
  author: "Muhammad Rehan Saeed"
  keywords: ".NET,C#,Reactive Extensions,Rx,Timer"
  "og:description": "You should definitely consider using Reactive Extensions (Rx) is as a direct replacement for .NET Timers. This post will explain how."
  "og:image": "https://rehansaeed.com/_og/s/o_b99fe4d5c2e6ef8d.png"
  "og:image:alt": "Reactive Extensions (Rx) - Part 4 - Replacing Timers - Muhammad Rehan Saeed"
  "og:image:height": "630"
  "og:image:type": image/png
  "og:image:width": "1200"
  "og:title": "Reactive Extensions (Rx) - Part 4 - Replacing Timers"
  "twitter:image": "https://rehansaeed.com/_og/s/o_b99fe4d5c2e6ef8d.png"
  "twitter:image:alt": "Reactive Extensions (Rx) - Part 4 - Replacing Timers - Muhammad Rehan Saeed"
---

> Index of every page on this site: [llms.txt](https://rehansaeed.com/llms.txt)

# [Reactive Extensions (Rx) - Part 4 - Replacing Timers](https://rehansaeed.com/reactive-extensions-part4-replacing-timers/)

Posted 11 March 2014 - **3 min read**

![Reactive Extensions](https://rehansaeed.com/_ipx/f_png&s_2560x1440/images/hero/Reactive-Extensions-1366x768.png)

1. [Reactive Extensions (Rx) - Replacing C# Events](https://rehansaeed.com/reactive-extensions-part1-replacing-events/)
2. [Reactive Extensions (Rx) - Wrapping C# Events](https://rehansaeed.com/reactive-extensions-part2-wrapping-events/)
3. [Reactive Extensions (Rx) - Naming Conventions](https://rehansaeed.com/reactive-extensions-part3-naming-conventions/)
4. [Reactive Extensions (Rx) - Replacing Timers](https://rehansaeed.com/reactive-extensions-part4-replacing-timers/)
5. [Reactive Extensions (Rx) - Awaiting Observables](https://rehansaeed.com/reactive-extensions-part5-awaiting-observables/)
6. [Reactive Extensions (Rx) - Task ToObservable](https://rehansaeed.com/reactive-extensions-part6-task-toobservable/)
7. [Reactive Extensions (Rx) - Sample Events](https://rehansaeed.com/reactive-extensions-part7-sample-events/)
8. [Reactive Extensions (Rx) - Timeouts](https://rehansaeed.com/reactive-extensions-rx-part-8-timeouts/)

Reactive Extensions (Rx) is a huge library. In this series of blog posts I've tried to illustrate real world applications where using Rx can significantly improve and/or simplify your code. So far I've talked about using Rx to replace standard C# events and also wrapping C# events with observables.

In this post I'm going to talk about another area where Rx provides a nicer API surface, as compared to an existing .NET API. In particular, I'm talking about the .NET Timers. There are a few different timers available in the .NET framework. The main ones being [System.Threading.Timer](http://msdn.microsoft.com/en-us/library/system.threading.timer%28v=vs.110%29.aspx) and [System.Timers.Timer](http://msdn.microsoft.com/en-us/library/system.timers.timer%28v=vs.110%29.aspx). Each one has their pros and cons but I'm not going to go into which ones are better as that's a whole [other conversation](http://stackoverflow.com/questions/1416803/system-timers-timer-vs-system-threading-timer).

# Existing .NET Timers Link to this section

Below is a very simple example of how to use the `System.Timers.Timer` (`System.Threading.Timer` is very similar). We new-up a `Timer` with the number of milliseconds we want to timer to raise it's `Elapsed` event, register for the `Elasped` event and finally start the timer.

```cs
public void StartTimer()
{
    Timer timer = new Timer(5000);
    timer.Elapsed += this.OnTimerElapsed;
    timer.Start();
}

private void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
    // Do Stuff Here
    Console.WriteLine(e.SignalTime);
    // Console WriteLine Prints
    // 11/03/2014 10:58:35
    // 11/03/2014 10:58:40
    // 11/03/2014 10:58:45
    // ...
}
```

# Reactive Extensions (Rx) Timers Link to this section

Now here is how to do almost the exact same thing with Reactive Extensions. In this scenario we use the `Interval` method to specify the timer interval and simply subscribe to the observable. The only difference is that we don't get a `DateTime` with the time of the timer elapsed event but an integer representing the number of times the timer elapsed delegate has been fired (Much more useful in my opinion, as you can always derive the time from this number).

```cs
public void StartTimer()
{
    Observable
        .Interval(TimeSpan.FromSeconds(5))
        .Subscribe(
            x =>
            {
                // Do Stuff Here
                Console.WriteLine(x);
                    // Console WriteLine Prints
                    // 0
                    // 1
                    // 2
                    // ...
            });
}
```

But that's not all, Reactive Extensions provides another method which can be quite useful. In the example below which looks almost exactly the same, we use the `Timer` method instead of `Interval`. This method only calls the timer elapsed delegate once.

```cs
public void StartTimerAndFireOnce()
{
    Observable
        .Timer(TimeSpan.FromSeconds(5))
        .Subscribe(
            x =>
            {
                // Do Stuff Here
                Console.WriteLine(x);
                // Console WriteLine Prints
                // 0
            });
}
```

The `Timer` method has lots of overloads which you can take a look at. The example below calls the timer elapsed delegate every five seconds but only starts to do so, after a minute has passed.

```cs
public void StartTimerInOneMinute()
{
    Observable
        .Timer(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5))
        .Subscribe(
            x =>
            {
                // Do Stuff Here
                Console.WriteLine(x);
                // Console WriteLine Prints
                // 0
                // 1
                // 2
                // ...
            });
}
```

The final thing you need to know about the `Interval` and `Timer` methods is that they can optionally take an `IScheduler` as a final parameter. This allows the timer elapsed delegate to be run on any thread of your choosing. In the example below we are subscribing the event on the WPF UI thread. There are several other `Scheduler`'s you can use, so just take a look.

```cs
public void StartTimerOnUIThread()
{
    Observable
        .Interval(TimeSpan.FromSeconds(5), DispatcherScheduler.Current)
        .Subscribe(
            x =>
            {
                // Do UI Stuff Here
            });
}
```

# Conclusions Link to this section

If you haven't started using Reactive Extensions yet, then here is yet another reason to get going. What I have not shown in this post is the shear superhuman power you get when you use the Linq methods to modify your observable just before you make the call to `Subscribe`.

## Web Mentions

[What's this?](https://en.wikipedia.org/wiki/Webmention)

### 0 Linked

### 0 Replies

## GitHub Comments

### 3 Comments

[Comment on GitHub](https://github.com/RehanSaeed/rehansaeed.github.io/issues/106)

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

### [RehanSaeed](https://github.com/RehanSaeed)

Owner

12 May 2020

[![Michael Khalsa](https://camo.githubusercontent.com/39875530cf64e8c9ca7d0451058a5641b756fa38bb6119951f7831992b24ff8c/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f63316633336461653736356634393263316632653364353364316633303537373f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/39875530cf64e8c9ca7d0451058a5641b756fa38bb6119951f7831992b24ff8c/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f63316633336461653736356634393263316632653364353364316633303537373f733d393626643d6d6d26723d67) **Michael Khalsa** commented on **2018-04-19 01:33:58**

Nice series, thanks!

Question about the timer example:  
 Is it best practice to add on .Dispose to the subscriber to have it cleanup (assuming yes), or will this happen automatically when the method completes. (showed example in vb)

```
Observable
    .Timer(TimeSpan.FromMilliseconds(intervalMs))
    .ObserveOn(Threading.SynchronizationContext.Current)
    .Subscribe(Function(x) StatusBar.Panels("statusPanelHeartbeat").Visible = False,
               Function(x) StatusBar.Panels("statusPanelHeartbeat").Visible = False)
    .Dispose()
```

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

### [RehanSaeed](https://github.com/RehanSaeed)

Owner

12 May 2020

[![Muhammad Rehan Saeed](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67) **[Muhammad Rehan Saeed](https://rehansaeed.com/)** commented on **2018-04-19 09:16:59**

> Nice series, thanks!
>
> Question about the timer example:  
>  Is it best practice to add on .Dispose to the subscriber to have it cleanup (assuming yes), or will this happen automatically when the method completes. (showed example in vb)
>
> ```
> Observable
>     .Timer(TimeSpan.FromMilliseconds(intervalMs))
>     .ObserveOn(Threading.SynchronizationContext.Current)
>     .Subscribe(Function(x) StatusBar.Panels("statusPanelHeartbeat").Visible = False,
>                Function(x) StatusBar.Panels("statusPanelHeartbeat").Visible = False)
>     .Dispose()
> ```

Here is a really good explanation:

https://stackoverflow.com/questions/7703366/reactive-observable-subscription-disposal

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

### [RehanSaeed](https://github.com/RehanSaeed)

Owner

12 May 2020

[![Michael Khalsa](https://camo.githubusercontent.com/39875530cf64e8c9ca7d0451058a5641b756fa38bb6119951f7831992b24ff8c/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f63316633336461653736356634393263316632653364353364316633303537373f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/39875530cf64e8c9ca7d0451058a5641b756fa38bb6119951f7831992b24ff8c/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f63316633336461653736356634393263316632653364353364316633303537373f733d393626643d6d6d26723d67) **Michael Khalsa** commented on **2018-04-22 00:29:47**

> Here is a really good explanation:
>
> https://stackoverflow.com/questions/7703366/reactive-observable-subscription-disposal

Thank you.

It was necessary to remove the `.Dispose` in this case to make it work correctly.

```json
{"@context":"https://schema.org","@graph":[{"@id":"https://rehansaeed.com/#website","@type":"WebSite","description":"Software Developer at Microsoft, YouTuber, Open Source Contributor and Blogger","inLanguage":"en-GB","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com/","author":{"@id":"https://rehansaeed.com/#identity"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://rehansaeed.com/?search={search_term_string}"},"query-input":"required name=search_term_string"}],"publisher":{"@id":"https://rehansaeed.com/#publisher"}},{"@id":"https://rehansaeed.com/reactive-extensions-part4-replacing-timers/#webpage","@type":"WebPage","dateModified":"2014-03-11T00:00:00+00:00","datePublished":"2014-03-11T00:00:00+00:00","description":"You should definitely consider using Reactive Extensions (Rx) is as a direct replacement for .NET Timers. This post will explain how.","name":"Reactive Extensions (Rx) - Part 4 - Replacing Timers","url":"https://rehansaeed.com/reactive-extensions-part4-replacing-timers/","breadcrumb":{"@id":"https://rehansaeed.com/reactive-extensions-part4-replacing-timers/#breadcrumb"},"isPartOf":{"@id":"https://rehansaeed.com/#website"},"potentialAction":[{"@type":"ReadAction","target":["https://rehansaeed.com/reactive-extensions-part4-replacing-timers/"]}]},{"@id":"https://rehansaeed.com/#identity","@type":"Person","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com/about/","image":{"@id":"https://rehansaeed.com/#/schema/image/1"},"sameAs":["https://github.com/RehanSaeed","https://www.linkedin.com/in/muhammad-rehan-saeed","https://stackoverflow.com/users/1212017/muhammad-rehan-saeed","https://www.youtube.com/c/MuhammadRehanSaeed","https://www.twitch.tv/rehansaeeduk"]},{"@id":"https://rehansaeed.com/#publisher","@type":"Organization","logo":"https://rehansaeed.com/images/schema/Publisher-600x60.png","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com"},{"@id":"https://rehansaeed.com/reactive-extensions-part4-replacing-timers/#article","@type":"Article","dateModified":"2014-03-11T00:00:00+00:00","datePublished":"2014-03-11T00:00:00+00:00","description":"You should definitely consider using Reactive Extensions (Rx) is as a direct replacement for .NET Timers. This post will explain how.","headline":"Reactive Extensions (Rx) - Part 4 - Replacing Timers","inLanguage":"en-GB","url":"https://rehansaeed.com/reactive-extensions-part4-replacing-timers/","author":{"@id":"https://rehansaeed.com/#identity"},"image":[{"@type":"ImageObject","url":"https://rehansaeed.com/images/hero/Reactive-Extensions-1366x768.png","caption":"Reactive Extensions","width":"1366","height":"768"}],"isPartOf":{"@id":"https://rehansaeed.com/reactive-extensions-part4-replacing-timers/#webpage"},"keywords":[".NET","C#","Reactive Extensions","Rx","Timer"],"mainEntityOfPage":{"@id":"https://rehansaeed.com/reactive-extensions-part4-replacing-timers/#webpage"},"publisher":{"@id":"https://rehansaeed.com/#publisher"}},{"@id":"https://rehansaeed.com/reactive-extensions-part4-replacing-timers/#breadcrumb","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","name":"Blog","item":"https://rehansaeed.com/","position":1},{"@type":"ListItem","name":"Reactive Extensions (Rx) - Part 4 - Replacing Timers","item":"https://rehansaeed.com/reactive-extensions-part4-replacing-timers/","position":2}]},{"@id":"https://rehansaeed.com/#/schema/image/1","@type":"ImageObject","contentUrl":"https://rehansaeed.com/images/author/Muhammad-Rehan-Saeed/Logo-512x512.png","inLanguage":"en-GB","url":"https://rehansaeed.com/images/author/Muhammad-Rehan-Saeed/Logo-512x512.png"}]}
```

## Sitemap

See the full [sitemap](https://rehansaeed.com/sitemap.md) for all pages.
