Article

A Scheduler for Tasks

Alex J. Champandard on June 1, 2007

Once you have a basic Task class to work with, you’ll be able to make behaviors by combining them together. However, you’ll quickly find it’s much easier to have all the tasks for an actor managed centrally. That’s what the scheduler is for.

Now, the implementation of this class can support as many features as you need (e.g. support for task priorities, guaranteeing the order of task execution), but a simplest version is sufficient to get started.

class Scheduler
{
public:
    bool run(Task&);
    bool halt(Task&);

    void update();

protected:
    std::vector m_ActiveTasks;
};

The run() function adds the client task to the list of active tasks, while the halt() function removes the client task. The boolean return value indicates if the scheduler managed to process the request (e.g. exceeded task limit, task not found), not the return value of the task. Tasks are only executed all together when the scheduler is asked to do so.

That’s what the update() function does, it runs through the list of active tasks and executes them one by one. If the task completes, then it is removed from the list. It’s important to note that the scheduler should typically support running and halting tasks while it is updating. Most of the times, you’ll only add one root task on initialization, and it will add tasks it depends on during the first execution.

Discussion 0 Comments

If you'd like to add a comment or question on this page, simply log-in to the site. You can create an account from the sign-up page if necessary... It takes less than a minute!