Wasim
Wasim

Reputation: 1935

Start task at once then by time interval using Rx framework

I'm trying to run my task immediately, then to run it by time interval. I wrote the following :

var syncMailObservable = Observable.Interval(TimeSpan.FromSeconds(15));
syncMailObservable.Subscribe(s => MyTask());

The problem is the task starts only after the 15 seconds. I need to run my task at the beginning then to continue by time interval.

How would I do that?

Upvotes: 8

Views: 2842

Answers (3)

POSIX-compliant
POSIX-compliant

Reputation: 4833

This question refers to the Interval method specifically, but the Timer method can be used to accomplish this cleanly.

The Timer method supports an initial delay (due time). Setting it as a time span of zero should start the task at once, and then run it at each interval.

 var initialDelay = new TimeSpan(0);
 var interval = TimeSpan.FromSeconds(15);

 Observable.Timer(initialDelay, interval, Scheduler.TaskPool)
     .Subscribe(_ => MyTask());

https://msdn.microsoft.com/en-us/library/hh229652(v=vs.103).aspx

Upvotes: 2

Enigmativity
Enigmativity

Reputation: 117029

You could do this:

var syncMailObservable =
    Observable
        .Interval(TimeSpan.FromSeconds(15.0), Scheduler.TaskPool)
        .StartWith(-1L);
syncMailObservable.Subscribe(s => MyTask());

Upvotes: 14

Ankur
Ankur

Reputation: 33637

Try this:

Observable.Return(0).Concat(Observable.Interval(TimeSpan.FromSeconds(15)))
.Subscribe(_ => MyTask());

Upvotes: 3

Related Questions