@@ -17,6 +17,39 @@ function Pool(options) {
17
17
this . _freeConnections = [ ] ;
18
18
this . _connectionQueue = [ ] ;
19
19
this . _closed = false ;
20
+ this . _recycleTimer = null ;
21
+ }
22
+
23
+ function recycleStaleConnections ( ) {
24
+ var now = Date . now ( ) ;
25
+ var min = null ;
26
+ for ( var i = 0 ; i < this . _freeConnections . length ; i ++ ) {
27
+ var lastused = this . _freeConnections [ i ] . _usedTimestamp ;
28
+
29
+ if ( lastused != undefined ) {
30
+ if ( ( now - lastused ) >= this . config . idleTimeout ) {
31
+ this . _freeConnections [ i ] . destroy ( ) ;
32
+ i -- ;
33
+ } else {
34
+ if ( min == null ) {
35
+ min = now - lastused
36
+ } else {
37
+ if ( ( now - lastused ) < min ) {
38
+ min = now - lastused ;
39
+ }
40
+ }
41
+ }
42
+ }
43
+ }
44
+ if ( min != null ) {
45
+ if ( min > 0 ) {
46
+ clearInterval ( this . _recycleTimer ) ;
47
+ this . _recycleTimer = setInterval ( recycleStaleConnections . bind ( this ) , this . config . idleTimeout ) ;
48
+ }
49
+ } else {
50
+ clearInterval ( this . _recycleTimer ) ;
51
+ this . _recycleTimer = null ;
52
+ }
20
53
}
21
54
22
55
Pool . prototype . getConnection = function ( cb ) {
@@ -138,6 +171,11 @@ Pool.prototype.releaseConnection = function releaseConnection(connection) {
138
171
throw new Error ( 'Connection already released' ) ;
139
172
} else {
140
173
// add connection to end of free queue
174
+ if ( this . config . idleTimeout > 0 && this . _recycleTimer == null ) {
175
+ this . _recycleTimer = setInterval ( recycleStaleConnections . bind ( this ) , this . config . idleTimeout ) ;
176
+ }
177
+
178
+ connection . _usedTimestamp = Date . now ( ) ;
141
179
this . _freeConnections . push ( connection ) ;
142
180
this . emit ( 'release' , connection ) ;
143
181
}
@@ -160,6 +198,10 @@ Pool.prototype.releaseConnection = function releaseConnection(connection) {
160
198
161
199
Pool . prototype . end = function ( cb ) {
162
200
this . _closed = true ;
201
+ if ( this . _recycleTimer ) {
202
+ clearInterval ( this . _recycleTimer ) ;
203
+ this . _recycleTimer = null ;
204
+ }
163
205
164
206
if ( typeof cb !== 'function' ) {
165
207
cb = function ( err ) {
0 commit comments