root/lu/LUTimer.lua

Revision 814 (checked in by rsz, 4 years ago)

cleanup

Line 
1 --------------------------------------------------------------------------------
2 -- Title:               LUTimer.lua
3 -- Description:         Like a square peg in a round hole
4 -- Author:              Raphaël Szwarc http://alt.textdrive.com/lua/
5 -- Creation Date:       February 1, 2005
6 -- Legal:               Copyright (C) 2005 Raphaël Szwarc
7 --------------------------------------------------------------------------------
8
9 -- import dependencies
10 local LUObject = require( "LUObject" )
11 local LUTask = require( "LUTask" )
12 local os = require( "os" )
13
14 -- define the class
15 local super = LUObject
16 local self = super()
17
18 -- initialization method
19 function self:init( aTarget, anInterval, shouldRepeat )
20         self = super.init( self )
21
22         self._target = aTarget
23         self._interval = anInterval
24         self._shouldRepeat = shouldRepeat
25        
26         return self
27 end       
28
29 -- method to access the timer interval
30 function self:interval()
31         return self._interval
32 end
33
34  -- method to access the timer target
35 function self:target()
36         return self._target
37 end
38
39  -- method to access the shouldRepeat variable
40 function self:shouldRepeat()
41         if self._shouldRepeat == nil then
42                 self._shouldRepeat = false
43         end
44
45         return self._shouldRepeat
46 end
47
48  -- method to stop this timer
49 function self:stop()
50         self._shouldRepeat = false
51
52         return self
53 end
54
55  -- method to access the clock
56 function self:clock()
57         if self._clock == nil then
58                 self._clock = os.clock()
59         end
60        
61         return self._clock
62 end
63
64  -- method to reset the clock
65 function self:resetClock()
66         self._clock = nil
67 end
68
69 -- method to start this reader task
70 function self:start()
71         if self._task == nil then
72                 self:task():run()
73         end
74        
75         return self
76 end
77
78 -- method to access this reader task
79 function self:task()
80         if self._task == nil then
81                 self._task = LUTask( self )
82         end
83        
84         return self._task
85 end
86
87  -- method to run the timer
88 function self:run()
89         repeat
90                 if ( os.clock() - self:clock() ) >= self:interval() then
91                         self:target():run( self )
92                         self:resetClock()
93                 end
94                
95                 LUTask:yield()
96         until self:shouldRepeat() == false
97        
98         return self
99 end
100
101 return self
Note: See TracBrowser for help on using the browser.