aboutsummaryrefslogtreecommitdiff
path: root/src/libjin/Time/Timer.cpp
blob: cfdb4bdf9d6966f4a8b9a49f622326d426a281f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include "../modules.h"
#if JIN_MODULES_TIME

#include "Timer.h"

namespace jin
{
namespace time
{


    Timers::Timers()
        : timers()
    {
    }

    Timers::~Timers()
    {
        for (int i = 0; i < timers.size(); ++i)
            delete timers[i];
    }

    void Timers::update(int ms)
    {
        std::vector<Timer*>::iterator it = timers.begin();
        for (; it != timers.end(); )
        {
            if (!(*it)->process(ms))
            {
                Timer* t = *it;
                timers.erase(it);
                delete t;
                return;
            }
            ++it;
        }
    }

    void Timers::every(int ms, timer_callback callback, void* p)
    {
        Timer* t = new Timer(Timer::EVERY, ms, 0, callback, p);
        timers.push_back(t);
    }

    void Timers::after(int ms, timer_callback callback, void* p)
    {
        Timer* t = new Timer(Timer::AFTER, ms, 0, callback, p);
        timers.push_back(t);
    }

    void Timers::repeat(int ms, int count, timer_callback callback, void* p)
    {
        Timer* t = new Timer(Timer::REPEAT, ms, count, callback, p);
        timers.push_back(t);
    }

    Timers::Timer::Timer(Type t, int d, int c, timer_callback f, void* p)
        : type(t)
        , duration(d)
        , count(c)
        , tickdown(d)
        , countdown(c)
        , callback(f)
        , paramters(p)
    {
    }

    Timers::Timer::~Timer()
    {
    }

    bool Timers::Timer::process(int ms)
    {
        tickdown -= ms; 
        if (tickdown <= 0)
        {
            tickdown = duration;
            if (callback != nullptr)
                callback(paramters);
            if (type == EVERY)
            {
            }
            else if (type == AFTER)
            {
                return false;
            }
            else if (type == REPEAT)
            {
                --countdown;
                if (countdown <= 0)
                    return false;
            }
        }
        return true;
    }

}
}

#endif // JIN_MODULES_TIME