2007-09-19 19:50:54 UTC
previous
next
#include <boost/thread.hpp>
#include <boost/utility.hpp>
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include "scheduler.h"
#include "log.h"
namespace Scheduler
{
boost::scoped_ptr<Manager> manager;
Manager::Manager()
{
log::debug("Starting scheduler thread");
_thread.reset(new boost::thread(boost::bind(&Manager::start, this)));
}
Manager::~Manager()
{
log::debug("Stopping scheduler thread");
_io_service_work.reset();
_io_service.interrupt();
// Thread may not have been created correctly, so check first
if (_thread)
_thread->join();
}
void Manager::start()
{
_io_service_work.reset(new boost::asio::io_service::work(_io_service));
_io_service.run();
}
void Manager::add_task(
boost::shared_ptr<Task> task,
boost::posix_time::time_duration time_til_next)
{
_io_service.post(boost::bind(&Manager::add_task_int, this, task, time_til_next));
}
void Manager::add_task_int(
boost::shared_ptr<Task> task,
boost::posix_time::time_duration time_til_next)
{
boost::shared_ptr<boost::asio::deadline_timer> timer(
new boost::asio::deadline_timer(_io_service, time_til_next));
_tasks.push_back(TaskInfo(task, timer));
timer->async_wait(boost::bind(&Manager::execute_task, this, _1, _tasks.back()));
}
void Manager::execute_task(
const boost::asio::error& error,
TaskInfo task_info)
{
if (error == boost::asio::error::operation_aborted)
return;
else if (error)
{
// TODO: Handle error
return;
}
boost::posix_time::time_duration time_til_next = task_info.task->start_task();
task_info.timer->expires_from_now(time_til_next);
task_info.timer->async_wait(boost::bind(&Manager::execute_task, this, _1, task_info));
}
}