@@ -190,22 +190,47 @@ def process_count
190
190
pcount
191
191
end
192
192
193
- def initial_wait
194
- # periodically clean out the `processes` set in Redis which can collect
195
- # references to dead processes over time. The process count affects how
196
- # often we scan for scheduled jobs.
197
- ps = Sidekiq ::ProcessSet . new ( false )
198
- ps . cleanup if rand ( 1000 ) % 10 == 0 # only cleanup 10% of the time
193
+ # A copy of Sidekiq::ProcessSet#cleanup because server
194
+ # should never depend on sidekiq/api.
195
+ def cleanup
196
+ # dont run cleanup more than once per minute
197
+ return 0 unless Sidekiq . redis { |conn | conn . set ( "process_cleanup" , "1" , nx : true , ex : 60 ) }
199
198
200
- # Have all processes sleep between 5-15 seconds. 10 seconds
201
- # to give time for the heartbeat to register (if the poll interval is going to be calculated by the number
199
+ count = 0
200
+ Sidekiq . redis do |conn |
201
+ procs = conn . sscan_each ( "processes" ) . to_a
202
+ heartbeats = conn . pipelined { |pipeline |
203
+ procs . each do |key |
204
+ pipeline . hget ( key , "info" )
205
+ end
206
+ }
207
+
208
+ # the hash named key has an expiry of 60 seconds.
209
+ # if it's not found, that means the process has not reported
210
+ # in to Redis and probably died.
211
+ to_prune = procs . select . with_index { |proc , i |
212
+ heartbeats [ i ] . nil?
213
+ }
214
+ count = conn . srem ( "processes" , to_prune ) unless to_prune . empty?
215
+ end
216
+ count
217
+ end
218
+
219
+ def initial_wait
220
+ # Have all processes sleep between 5-15 seconds. 10 seconds to give time for
221
+ # the heartbeat to register (if the poll interval is going to be calculated by the number
202
222
# of workers), and 5 random seconds to ensure they don't all hit Redis at the same time.
203
223
total = 0
204
224
total += INITIAL_WAIT unless @config [ :poll_interval_average ]
205
225
total += ( 5 * rand )
206
226
207
227
@sleeper . pop ( total )
208
228
rescue Timeout ::Error
229
+ ensure
230
+ # periodically clean out the `processes` set in Redis which can collect
231
+ # references to dead processes over time. The process count affects how
232
+ # often we scan for scheduled jobs.
233
+ cleanup
209
234
end
210
235
end
211
236
end
0 commit comments