Newbie question concerning a simple thread

First off, I’m a RoR beginner and am new to web dev in general, so I’m
probably not going about this in the best way.

I’m trying to use thread.new to run an external application that has the
potential to take a few minutes. The external app takes some info that
the user has selected on the web site and creates a file from it. What
I want to happen is that, when the user clicks a link, a window pops up
and the external app is started, but the .rhtml file is not loaded in
the popup until the external app is completed. Here’s my code:

on the list page, from where they will click the link to run the
external app:

<%= link_to ‘External App’, :action => ‘extapp’, :popup =>
[‘new_window’, ‘height=300,width=600’] %>

in my controller:

def extapp
#create file

Thread.new {system(“extapp.exe”)}
end

in extapp.rhtml:
<%= link_to ‘Download’, :action => ‘dl_output_file’ %>

So my problem is, extapp.rhtml is loaded immediately, giving the user a
link to download the file even though it hasn’t been created yet. If I
remove thread.new, extapp.rhtml doesn’t load until the app is done, but
then there is no threading and you can’t do anything else.

Any help would be greatly appreciated, thanks!

zack wrote:

in my controller:

def extapp
#create file

Thread.new {system(“extapp.exe”)}
end

Threading has a trick to it. The app can finish processing before the
threads are finished. This bails out on the threads. You have to do a
tricky thing that ensures all threads are done before processing
continues. You can use Thread#join to do this.

THis is a typical example for a some threaded operations.

threads = []
threads << Thread.new { do_something(foo) }
threads << Thread.new { do_something_else(bar) }

threads.each do |thread|
thread.join
end

or in your simplified example its even easier:

Thread.new { system(“extapp.exe”) }.join

Your code will not continu past the join method call unless the thread
join is called on is completed.

zack wrote:

#create file
So my problem is, extapp.rhtml is loaded immediately, giving the user a
link to download the file even though it hasn’t been created yet. If I
remove thread.new, extapp.rhtml doesn’t load until the app is done, but
then there is no threading and you can’t do anything else.

Any help would be greatly appreciated, thanks!

You probably want to use Ajax:

Rails includes support for Ajax through the Prototype and
script.aculo.us JavaScript libraries though you can use something else
or roll your own if you like.


Michael W.