Created
July 9, 2009 21:50
-
-
Save sandro/144029 to your computer and use it in GitHub Desktop.
fork a long running process
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Spawn a long-running process in response to a POST request. The | |
request spawns a child and immediately redirects, making the request | |
non-blocking. The child changes the text on the index page from | |
"Running" to "Not running" after finishing its work. | |
Instructions: | |
ruby app.rb | |
visit http://localhost:4567 | |
push "Run" | |
notice the text says "Running" | |
Refresh until the text says "Not running" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'sinatra' | |
require 'haml' | |
module State | |
FILE_NAME = 'running' | |
def self.running? | |
File.exists? FILE_NAME | |
end | |
def self.reset! | |
File.unlink FILE_NAME | |
end | |
def self.run! | |
system 'touch', FILE_NAME | |
end | |
end | |
get '/' do | |
@running = State.running? | |
haml :index | |
end | |
get '/reset' do | |
State.reset! | |
redirect '/' | |
end | |
post '/' do | |
State.run! | |
pid = fork { sleep 2; State.reset! } | |
Process.detach pid | |
redirect '/' | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- if @running | |
Running | |
- else | |
Not running | |
%form{:action => "", :method => "post"} | |
%button{:type => "submit"} Run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment