I have a fairly simple Ruby script that downloads 2 very large files from 2 different locations.  Long story short.. it is cheaper for me from a bandwidth perspective (b/c of 95th percentile billing) to download both of the files at the same time.  I can’t exactly do this in my Ruby script if I write it that executes sequentially.  So I thought back to my Java days (YUCK!)  and decided to see if Ruby had a similar mechanism as Java for threading.  Turns out it does and its pretty easy to use.  My requirements are to download both files and continue with the script only after both files are downloaded.  So here is what I did:

#create a thread to download first file
t1 = Thread.new do

system(“/usr/local/bin/ruby /path/to/my/file/start_download.rb”)

end

#start the 2nd download

start_download2

while t1.status!=false

sleep 1

end

#continue

…….

Easy enough. I start by firing off a thread to download the first file, then I start download the 2nd file within the main script.   Then I check the status of the thread to see if its complete.  If so, I continue the execute of the main script.

Tags: ,