@@ -19,7 +19,6 @@ package monitor
19
19
import (
20
20
"fmt"
21
21
"sort"
22
- "time"
23
22
24
23
"github.com/spacemonkeygo/errors"
25
24
"github.com/spacemonkeygo/monotime"
@@ -30,12 +29,6 @@ const (
30
29
microsecondInNanoseconds = 1000
31
30
)
32
31
33
- // TaskCtx keeps track of a task as it is running.
34
- type TaskCtx struct {
35
- start time.Duration
36
- monitor * TaskMonitor
37
- }
38
-
39
32
// Start is a helper method for watching a task in a less error-prone way.
40
33
// Managing a task context yourself is tricky to get right - recover only works
41
34
// in deferred methods. Call out of a method that was deferred and it no longer
@@ -48,14 +41,16 @@ func (t *TaskMonitor) Start() func(*error) {
48
41
// NewContext creates a new context that is watching a live task. See Start
49
42
// or MonitorGroup.Task
50
43
func (t * TaskMonitor ) NewContext () * TaskCtx {
44
+ c := & TaskCtx {start : monotime .Monotonic (), monitor : t }
51
45
t .mtx .Lock ()
52
46
t .current += 1
53
47
t .total_started += 1
54
48
if t .current > t .highwater {
55
49
t .highwater = t .current
56
50
}
51
+ t .running [c ] = true
57
52
t .mtx .Unlock ()
58
- return & TaskCtx { start : monotime . Monotonic (), monitor : t }
53
+ return c
59
54
}
60
55
61
56
// Stats conforms to the Monitor interface
@@ -121,7 +116,7 @@ func (t *TaskMonitor) Stats(cb func(name string, val float64)) {
121
116
// Finish will re-panic any recovered panics (provided it wasn't a nil panic)
122
117
// after bookkeeping.
123
118
func (c * TaskCtx ) Finish (err_ref * error , rec interface {}) {
124
- duration_nanoseconds := int64 (monotime . Monotonic () - c . start )
119
+ duration_nanoseconds := int64 (c . ElapsedTime () )
125
120
var error_name string
126
121
var err error
127
122
if err_ref != nil {
@@ -151,6 +146,7 @@ func (c *TaskCtx) Finish(err_ref *error, rec interface{}) {
151
146
c .monitor .mtx .Lock ()
152
147
c .monitor .current -= 1
153
148
c .monitor .total_completed += 1
149
+ delete (c .monitor .running , c )
154
150
if err != nil {
155
151
c .monitor .errors [error_name ] += 1
156
152
if rec != nil {
@@ -170,3 +166,17 @@ func (c *TaskCtx) Finish(err_ref *error, rec interface{}) {
170
166
panic (rec )
171
167
}
172
168
}
169
+
170
+ // Running returns a list of tasks that are currently running. Each TaskCtx
171
+ // can tell how long it's been since the task was started, though keep in mind
172
+ // that the task might finish between calling (*TaskMonitor).Running() and
173
+ // (*TaskCtx).ElapsedTime()
174
+ func (t * TaskMonitor ) Running () (rv []* TaskCtx ) {
175
+ t .mtx .Lock ()
176
+ rv = make ([]* TaskCtx , 0 , len (t .running ))
177
+ for task_ctx := range t .running {
178
+ rv = append (rv , task_ctx )
179
+ }
180
+ t .mtx .Unlock ()
181
+ return rv
182
+ }
0 commit comments