Design for Task Scheduler in .NET 4 (Task Parallel Library)

I am trying to create a service that performs scheduled tasks in an asynchronous (and parallel) way using TPL.

The basic requirement is that for many different tasks, each of them has its own scheduled rates (some of which will be executed every second, others 30 seconds, others 5 minutes, etc.), which will be performed simultaneously. And I'm not sure of the best way to do this, especially considering that the ConcurrentBag (which I saw as the owner of all future tasks) does not contain methods for selecting the collections of tasks that need to be performed.

It also means that I cannot use WaitAny or WaitAll, as these short-lived tasks must end and request on their own.

How can I continue this?

Edit:

Ok, basically my design:

A ScheduledTask, which is a wrapper for a task with an assigned DateTime value. The letter of them is stored in ConcurrentBag

The controller that polls the ConcurrentBag (currently only a while (true) loop, but may be a Timer or similar), deleting all scheduled and Start () ones.

Each ScheduledTask contains a link to the ConcurrentBag and completes a new instance of itself when it completes, with a new ScheduledTime value.

This project seems to be working so far, but there is something about every Task containing a link to the ConcurrentBag that does not suit me. Any comments or design suggestions would be appreciated.

+3
source share
4 answers

, .

-

MyTask SomeAction() {
    DateTime now = DateTime.Now;
    DoSomeTask();
    return new MyTask { StartTime = now.AddMinutes(1), DoSomething = SomeAction }
}

:

List<MyTask> tasklist = new List<MyTask>();

public void Scheduler() {
    for (;;)
        DateTime now = DateTime.Now;

        List<MyTask> tasksToRun;
        lock (taskList) 
            taskToRun = taskList.Where(x => x.StartTime <= now)
                                .ToList();

        var tasks = tasksToRun.Select(x => RunTask(x))
                              .ToArray();
        Thread.Sleep(1000);
    }
}

private Task<MyTask> RunTask(MyTask myTask) {
    lock (taskList)
        tasklist.Remove(myTask);

    return Task<MyTask>.Factory.StartNew(myTask.DoSomething())
                               .ContinueWith(t => {
                                                      if (t.Result != null)
                                                          lock (taskList)
                                                              taskList.Add(t.Result);
                                                  });
}
+1

EventLoopScheduler RX?

Rx , EventLoopScheduler .

RX, Observable.Interval(timespan, scheduler).Subscribe(action).

+2

, ( TPL, ). , ; . SourceForge.

0

All Articles