Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a good way to run periodic tasks using Rx, with a single concurrent execution restriction?

I want to run periodic tasks in with a restriction that at most only one execution of a method is running at any given time.

I was experimenting with Rx, but I am not sure how to impose at most once concurrency restriction.

var timer = Observable.Interval(TimeSpan.FromMilliseconds(100));
timer.Subscribe(tick => DoSomething());

Additionally, if a task is still running, I want the subsequent schedule to elapse. i.e I don't want the tasks to queue up and cause problems.

I have 2 such tasks to execute periodically. The tasks being executed is currently synchronous. But, I could make them async if there is a necessity.

like image 997
smartnut007 Avatar asked Jul 14 '15 06:07

smartnut007


1 Answers

You should have tested your code as is because this is exactly what Rx imposes already.

Try this as a test:

void Main()
{
    var timer = Observable.Interval(TimeSpan.FromMilliseconds(100));
    using (timer.Do(x => Console.WriteLine("!")).Subscribe(tick => DoSomething()))
    {
        Console.ReadLine();
    }
}

private void DoSomething()
{
    Console.Write("<");
    Console.Write(DateTime.Now.ToString("HH:mm:ss.fff"));
    Thread.Sleep(1000);
    Console.WriteLine(">");
}

When you run this you'll get this kind of output:

!
<16:54:57.111>
!
<16:54:58.112>
!
<16:54:59.113>
!
<16:55:00.113>
!
<16:55:01.114>
!
<16:55:02.115>
!
<16:55:03.116>
!
<16:55:04.117>
!
<16:55:05.118>
!
<16:55:06.119

It is already ensuring that there's no overlap.

like image 95
Enigmativity Avatar answered Sep 22 '22 23:09

Enigmativity