Question

I am launching casperJS scripts from my controller as this:

output = `casperjs #{path_to_file} '#{url}#'`

And sometimes, for several reasons the casperjs script might hang, or might take a long time. I am wondering if there is anyway I can set a timeout in my controller to just kill the process and control it. Is that possible?

Was it helpful?

Solution

require 'timeout'
Timeout.timeout(<seconds>) do
   output = `casperjs #{path_to_file} '#{url}#'`
end

This will raise a Timeout::Error exception if the script doesn't finish within the given time

Edit(to kill the process after timeout)

require 'timeout'
pipe_cmd_in, pipe_cmd_out = IO.pipe
pid = Process.spawn("casperjs #{path_to_file} '#{url}#'", :out => pipe_cmd_out, :err => pipe_cmd_out)
Timeout.timeout(<seconds>) do
   Process.wait(pid)
   pipe_cmd_out.close
   output = pipe_cmd_in.read;
end
rescue Timeout::Error
   Process.kill('TERM', pid)
end

Have a look at the teminator gem as well. It will help if you have many system calls to deal with

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top