mercredi 2 novembre 2016

Boost - periodic task scheduler

I'm trying to figure out a simple scheduler for periodic tasks. The idea is to provide a mean to schedule periodic execution of std::function<void()> with any given time interval which would be a multiplication of a second. I was trying to write it with the use of boost::asio, but so far I end up with strange behaviour - only one of two scheduled tasks is being repeatedly executed, but it don't follow the interval.

Here is the code:

class PeriodicTask
{
public: 
     PeriodicTask(boost::asio::io_service * ioService, int interval, std::function<void()> task)
     : ioService(ioService), 
       interval(interval), 
       task(std::make_shared<std::function<void()>>(task)),
       timer(std::make_shared<boost::asio::deadline_timer>(*ioService, boost::posix_time::seconds(interval)))
    {}

    void execute()
    {
        task->operator()();
        timer->expires_at(timer->expires_at() + boost::posix_time::seconds(interval));
        timer->async_wait(boost::bind(&PeriodicTask::execute,this));
    }

private:
     std::shared_ptr<boost::asio::io_service> ioService;
     std::shared_ptr<boost::asio::deadline_timer> timer;
     std::shared_ptr<std::function<void()>> task;
     int interval;
};

class PeriodicScheduler
{
public:
    void run()
    {
        for each (auto task in tasks)
        {
            task.execute();
        }
        io_service.run();
    }
    void  addTask(std::function<void()> task, int interval)
    {
        tasks.push_back(PeriodicTask(&io_service, interval, task));
    }
    boost::asio::io_service io_service;

private:
    std::vector<PeriodicTask> tasks;
};


void printCPUUsage()
{
    std::cout << "CPU usage: " << std::endl;
}

void printMemoryUsage()
{
    std::cout << "CPU usage: " << std::endl;
}
int _tmain(int argc, _TCHAR* argv[])
{   
    PeriodicScheduler scheduler;

    scheduler.addTask(printCPUUsage, 5);
    scheduler.addTask(printMemoryUsage, 10);

    scheduler.run();

    return 0;
}

Does anyone know what could cause the problem ? Or happen to know better approach to the problem ?

Many Thanks!

Aucun commentaire:

Enregistrer un commentaire