Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 615
Wasim Avatar asked Oct 16 '11 13:10

Wasim


3 Answers

You could do this:

var syncMailObservable =
    Observable
        .Interval(TimeSpan.FromSeconds(15.0), Scheduler.TaskPool)
        .StartWith(-1L);
syncMailObservable.Subscribe(s => MyTask());
like image 172
Enigmativity Avatar answered Oct 12 '22 23:10

Enigmativity


Try this:

Observable.Return(0).Concat(Observable.Interval(TimeSpan.FromSeconds(15)))
.Subscribe(_ => MyTask());
like image 41
Ankur Avatar answered Oct 13 '22 00:10

Ankur


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

like image 41
POSIX-compliant Avatar answered Oct 13 '22 01:10

POSIX-compliant