Home > Net >  Asynchronous, non-blocking background execution in Ruby script
Asynchronous, non-blocking background execution in Ruby script

Time:01-14

I am trying to execute some code in a non-blocking way.

In my real scenario, this would be an expensive SQL query in a Ruby on Rails app, however, as a test for replicating the scenario, I made this Ruby script:

#!/usr/bin/env ruby

require 'async'

puts 'hello'

Async do
  sleep 2
  puts 'hi'
end

puts 'there'

My expectation would be to see:

hello
there

immediately. However, what I actually get, is:

hello
hi
there

after two seconds.

I don't care about the return value of the async call — I just want to execute some code in the background and exit immediately.

Is there a way to do this in Ruby 3?

CodePudding user response:

You easily do this using a thread.

puts 'hello'

# Async == Thread
Thread.new do
  sleep 2
  puts 'hi'
end

puts 'there'
``
  •  Tags:  
  • ruby
  • Related