blob: 8289c577e99b8a764fbda958cbee1b17908913c8 [file] [log] [blame]
Alexander Afanasyev1b0e0082013-01-17 16:48:26 -08001/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
2/*
3 * Copyright (c) 2013 University of California, Los Angeles
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation;
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
19 * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
20 */
21
22#ifndef TASK_H
23#define TASK_H
24
25#define _OVERRIDE
26#ifdef __GNUC__
27#if __GNUC_MAJOR >= 4 && __GNUC_MINOR__ >= 7
28 #undef _OVERRIDE
29 #define _OVERRIDE override
30#endif // __GNUC__ version
31#endif // __GNUC__
32
33#include <boost/function.hpp>
34#include <boost/shared_ptr.hpp>
35#include <sys/time.h>
36
37//////////////////////////////////////////////////
38// forward declarations
39class Task;
40typedef boost::shared_ptr<Task> TaskPtr;
41
42class Scheduler;
43typedef boost::shared_ptr<Scheduler> SchedulerPtr;
44
45struct event;
46//////////////////////////////////////////////////
47
48
49/**
50 * @brief Base class for a task
51 */
52class Task
53{
54public:
55 // callback of this task
56 typedef boost::function<void ()> Callback;
57 // tag identifies this task, should be unique
58 typedef std::string Tag;
59 // used to match tasks
60 typedef boost::function<bool (const TaskPtr &task)> TaskMatcher;
61
62 // Task is associated with Schedulers due to the requirement that libevent event is associated with an libevent event_base
63 Task(const Callback &callback, const Tag &tag, const SchedulerPtr &scheduler);
64 virtual ~Task();
65
66 virtual void
67 run() = 0;
68
69 Tag
70 tag() { return m_tag; }
71
72 event *
73 ev() { return m_event; }
74
75 timeval *
76 tv() { return m_tv; }
77
78 // Task needs to be resetted after the callback is invoked if it is to be schedule again; just for safety
79 // it's called by scheduler automatically when addTask or rescheduleTask is called;
80 // Tasks should do preparation work here (e.g. set up new delay, etc. )
81 virtual void
82 reset() = 0;
83
84 // set delay
85 // This overrides whatever delay kept in m_tv
86 void
87 setTv(double delay);
88
89protected:
90 Callback m_callback;
91 Tag m_tag;
92 SchedulerPtr m_scheduler;
93 bool m_invoked;
94 event *m_event;
95 timeval *m_tv;
96};
97
98
99#endif // TASK_H