Adding two small helpers to scheduler
diff --git a/scheduler/scheduler.cc b/scheduler/scheduler.cc
index 2806075..ee6a124 100644
--- a/scheduler/scheduler.cc
+++ b/scheduler/scheduler.cc
@@ -20,9 +20,14 @@
*/
#include "scheduler.h"
+#include "one-time-task.h"
+#include "periodic-task.h"
+
#include <utility>
+#include <boost/make_shared.hpp>
using namespace std;
+using namespace boost;
#define EVLOOP_NO_EXIT_ON_EMPTY 0x04
@@ -91,24 +96,45 @@
m_thread.join();
}
-bool
-Scheduler::addTask(const TaskPtr &task)
+TaskPtr
+Scheduler::scheduleOneTimeTask (SchedulerPtr scheduler, double delay,
+ const Task::Callback &callback, const Task::Tag &tag)
{
- TaskPtr newTask = task;
+ TaskPtr task = make_shared<OneTimeTask> (callback, tag, scheduler, delay);
+ if (scheduler->addTask (task))
+ return task;
+ else
+ return TaskPtr ();
+}
+TaskPtr
+Scheduler::schedulePeriodicTask (SchedulerPtr scheduler, IntervalGeneratorPtr delayGenerator,
+ const Task::Callback &callback, const Task::Tag &tag)
+{
+ TaskPtr task = make_shared<PeriodicTask> (callback, tag, scheduler, delayGenerator);
+
+ if (scheduler->addTask (task))
+ return task;
+ else
+ return TaskPtr ();
+}
+
+bool
+Scheduler::addTask(TaskPtr newTask)
+{
if (addToMap(newTask))
{
newTask->reset();
int res = evtimer_add(newTask->ev(), newTask->tv());
if (res < 0)
{
- cout << "evtimer_add failed for " << task->tag() << endl;
+ cout << "evtimer_add failed for " << newTask->tag() << endl;
}
return true;
}
else
{
- cout << "fail to add task: " << task->tag() << endl;
+ cout << "fail to add task: " << newTask->tag() << endl;
}
return false;
diff --git a/scheduler/scheduler.h b/scheduler/scheduler.h
index 83b9926..e783cf0 100644
--- a/scheduler/scheduler.h
+++ b/scheduler/scheduler.h
@@ -38,6 +38,10 @@
#include <sys/time.h>
#include "task.h"
+#include "interval-generator.h"
+
+class Scheduler;
+typedef boost::shared_ptr<Scheduler> SchedulerPtr;
/**
* @brief Scheduler class
@@ -56,9 +60,18 @@
virtual void
shutdown();
+ // helper method to schedule one-time task
+ static TaskPtr
+ scheduleOneTimeTask (SchedulerPtr scheduler, double delay, const Task::Callback &callback, const Task::Tag &tag);
+
+ // helper method to schedule periodic task
+ static TaskPtr
+ schedulePeriodicTask (SchedulerPtr scheduler, IntervalGeneratorPtr delayGenerator,
+ const Task::Callback &callback, const Task::Tag &tag);
+
// if task with the same tag exists, the task is not added and return false
virtual bool
- addTask(const TaskPtr &task);
+ addTask(TaskPtr task);
// delete task by task->tag, regardless of whether it's invoked or not
virtual void
@@ -117,9 +130,6 @@
boost::thread m_thread;
};
-class Scheduler;
-typedef boost::shared_ptr<Scheduler> SchedulerPtr;
-
struct SchedulerException : virtual boost::exception, virtual std::exception { };
#endif // SCHEDULER_H