Class: Rbitter::DLThread
- Inherits:
-
Object
- Object
- Rbitter::DLThread
- Defined in:
- lib/rbitter/dlthread.rb
Constant Summary collapse
- MAX_THREADS =
20
Instance Method Summary collapse
- #<<(url_array) ⇒ Object
-
#initialize(dlfolder, large_flag) ⇒ DLThread
constructor
A new instance of DLThread.
- #job_cleanup ⇒ Object
Constructor Details
#initialize(dlfolder, large_flag) ⇒ DLThread
Returns a new instance of DLThread.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/rbitter/dlthread.rb', line 10 def initialize(dlfolder, large_flag) @dest = dlfolder if not File.directory?(dlfolder) warn "[dlthread] Given download location is not available for downloading." warn "[dlthread] Fallback to current directory." @dest = "./" end if large_flag.nil? @large_image = false else @large_image = large_flag end @pool = Array.new end |
Instance Method Details
#<<(url_array) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/rbitter/dlthread.rb', line 27 def <<(url_array) if @pool.length >= MAX_THREADS job_cleanup end download_task = Thread.new do url_array.each { |url| uri = URI.parse(@large_image ? url + ":large" : url) begin Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme.downcase == 'https') { |h| req = Net::HTTP::Get.new uri.request_uri h.request(req) { |res| case res when Net::HTTPOK fname = File.basename(url) puts "[fetch] remote: #{uri.path} => local: #{fname}" open(File.join(@dest, fname), "wb") { |file| res.read_body { |chunk| file.write(chunk) } } end } } rescue => e puts "[dlthread] exception from thread -> #{e.to_s}" end } end @pool.push download_task end |
#job_cleanup ⇒ Object
60 61 62 63 64 65 66 67 68 |
# File 'lib/rbitter/dlthread.rb', line 60 def job_cleanup until @pool.empty? dlthrd = @pool.shift if dlthrd.join(5).nil? puts "[dlthread] #{dlthrd.to_s} is still running. (timeout: 5sec)" end end end |