blob: bd14296e03aa623f3cb8a2721607b1567b82bf00 [file] [log] [blame]
Jeff Thompsonfa306642013-06-17 15:06:57 -07001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
2/*
3 * Copyright (c) 2013, Regents of the University of California
4 * Alexander Afanasyev
5 * Zhenkai Zhu
6 *
7 * BSD license, See the LICENSE file for more information
8 *
9 * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
10 * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
11 */
12
13#ifndef TASK_H
14#define TASK_H
15
16#define _OVERRIDE
17#ifdef __GNUC__
18#if __GNUC_MAJOR >= 4 && __GNUC_MINOR__ >= 7
19 #undef _OVERRIDE
20 #define _OVERRIDE override
21#endif // __GNUC__ version
22#endif // __GNUC__
23
24#include <boost/function.hpp>
25#include <boost/shared_ptr.hpp>
26#include <boost/enable_shared_from_this.hpp>
27#include <sys/time.h>
28
29//////////////////////////////////////////////////
30// forward declarations
31class Task;
32typedef boost::shared_ptr<Task> TaskPtr;
33
34class Scheduler;
35typedef boost::shared_ptr<Scheduler> SchedulerPtr;
36
37struct event;
38//////////////////////////////////////////////////
39
40
41/**
42 * @brief Base class for a task
43 */
44class Task : public boost::enable_shared_from_this<Task>
45{
46public:
47 // callback of this task
48 typedef boost::function<void ()> Callback;
49 // tag identifies this task, should be unique
50 typedef std::string Tag;
51 // used to match tasks
52 typedef boost::function<bool (const TaskPtr &task)> TaskMatcher;
53
54 // Task is associated with Schedulers due to the requirement that libevent event is associated with an libevent event_base
55 Task(const Callback &callback, const Tag &tag, const SchedulerPtr &scheduler);
56 virtual ~Task();
57
58 virtual void
59 run() = 0;
60
61 Tag
62 tag() { return m_tag; }
63
64 event *
65 ev() { return m_event; }
66
67 timeval *
68 tv() { return m_tv; }
69
70 // Task needs to be resetted after the callback is invoked if it is to be schedule again; just for safety
71 // it's called by scheduler automatically when addTask or rescheduleTask is called;
72 // Tasks should do preparation work here (e.g. set up new delay, etc. )
73 virtual void
74 reset() = 0;
75
76 // set delay
77 // This overrides whatever delay kept in m_tv
78 void
79 setTv(double delay);
80
81 void
82 execute();
83
84protected:
85 Callback m_callback;
86 Tag m_tag;
87 SchedulerPtr m_scheduler;
88 bool m_invoked;
89 event *m_event;
90 timeval *m_tv;
91};
92
93
94#endif // TASK_H