blob: 47029067b635a5493c24e9f77781d3e6003a431d [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#include "task.h"
23#include "scheduler.h"
24
Alexander Afanasyev3f101ec2013-01-17 16:58:03 -080025static void
Alexander Afanasyev1b0e0082013-01-17 16:48:26 -080026eventCallback(evutil_socket_t fd, short what, void *arg)
27{
28 Task *task = static_cast<Task *>(arg);
Zhenkai Zhu1888f742013-01-28 12:47:33 -080029 task->execute();
Alexander Afanasyev1b0e0082013-01-17 16:48:26 -080030 task = NULL;
31}
32
33Task::Task(const Callback &callback, const Tag &tag, const SchedulerPtr &scheduler)
34 : m_callback(callback)
35 , m_tag(tag)
36 , m_scheduler(scheduler)
37 , m_invoked(false)
38 , m_event(NULL)
39 , m_tv(NULL)
40{
41 m_event = evtimer_new(scheduler->base(), eventCallback, this);
42 m_tv = new timeval;
43}
44
45Task::~Task()
46{
47 if (m_event != NULL)
48 {
49 event_free(m_event);
50 m_event = NULL;
51 }
52
53 if (m_tv != NULL)
54 {
55 delete m_tv;
56 m_tv = NULL;
57 }
58}
59
60void
61Task::setTv(double delay)
62{
Alexander Afanasyev34edd4d2013-01-17 17:55:45 -080063 // Alex: when using abs function, i would recommend use it with std:: prefix, otherwise
64 // the standard one may be used, which converts everything to INT, making a lot of problems
Alexander Afanasyev1b0e0082013-01-17 16:48:26 -080065 double intPart, fraction;
Alexander Afanasyev34edd4d2013-01-17 17:55:45 -080066 fraction = modf(std::abs(delay), &intPart);
67
Alexander Afanasyev1b0e0082013-01-17 16:48:26 -080068 m_tv->tv_sec = static_cast<int>(intPart);
69 m_tv->tv_usec = static_cast<int>((fraction * 1000000));
70}
Zhenkai Zhu1888f742013-01-28 12:47:33 -080071
72void
73Task::execute()
74{
75 m_scheduler->execute(boost::bind(&Task::run, this));
76}