@@ -31,9 +31,9 @@ const DEFAULT_BUFFER_TIMEOUT_MS = 20_000;
31
31
export class BatchSpanProcessor implements SpanProcessor {
32
32
private readonly _bufferSize : number ;
33
33
private readonly _bufferTimeout : number ;
34
+
34
35
private _finishedSpans : ReadableSpan [ ] = [ ] ;
35
- private _lastSpanFlush = Date . now ( ) ;
36
- private _timer : NodeJS . Timeout ;
36
+ private _timer : NodeJS . Timeout | undefined ;
37
37
private _isShutdown = false ;
38
38
39
39
constructor ( private readonly _exporter : SpanExporter , config ?: BufferConfig ) {
@@ -43,13 +43,6 @@ export class BatchSpanProcessor implements SpanProcessor {
43
43
config && typeof config . bufferTimeout === 'number'
44
44
? config . bufferTimeout
45
45
: DEFAULT_BUFFER_TIMEOUT_MS ;
46
-
47
- this . _timer = setInterval ( ( ) => {
48
- if ( this . _shouldFlush ( ) ) {
49
- this . _flush ( ) ;
50
- }
51
- } , this . _bufferTimeout ) ;
52
- unrefTimer ( this . _timer ) ;
53
46
}
54
47
55
48
forceFlush ( ) : void {
@@ -73,7 +66,6 @@ export class BatchSpanProcessor implements SpanProcessor {
73
66
if ( this . _isShutdown ) {
74
67
return ;
75
68
}
76
- clearInterval ( this . _timer ) ;
77
69
this . forceFlush ( ) ;
78
70
this . _isShutdown = true ;
79
71
this . _exporter . shutdown ( ) ;
@@ -82,22 +74,33 @@ export class BatchSpanProcessor implements SpanProcessor {
82
74
/** Add a span in the buffer. */
83
75
private _addToBuffer ( span : ReadableSpan ) {
84
76
this . _finishedSpans . push ( span ) ;
77
+ this . _maybeStartTimer ( ) ;
85
78
if ( this . _finishedSpans . length > this . _bufferSize ) {
86
79
this . _flush ( ) ;
87
80
}
88
81
}
89
82
90
- private _shouldFlush ( ) : boolean {
91
- return (
92
- this . _finishedSpans . length >= 0 &&
93
- Date . now ( ) - this . _lastSpanFlush >= this . _bufferTimeout
94
- ) ;
95
- }
96
-
97
83
/** Send the span data list to exporter */
98
84
private _flush ( ) {
85
+ this . _clearTimer ( ) ;
86
+ if ( this . _finishedSpans . length === 0 ) return ;
99
87
this . _exporter . export ( this . _finishedSpans , ( ) => { } ) ;
100
88
this . _finishedSpans = [ ] ;
101
- this . _lastSpanFlush = Date . now ( ) ;
89
+ }
90
+
91
+ private _maybeStartTimer ( ) {
92
+ if ( this . _timer !== undefined ) return ;
93
+
94
+ this . _timer = setTimeout ( ( ) => {
95
+ this . _flush ( ) ;
96
+ } , this . _bufferTimeout ) ;
97
+ unrefTimer ( this . _timer ) ;
98
+ }
99
+
100
+ private _clearTimer ( ) {
101
+ if ( this . _timer !== undefined ) {
102
+ clearTimeout ( this . _timer ) ;
103
+ this . _timer = undefined ;
104
+ }
102
105
}
103
106
}
0 commit comments