Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Asynchronous, non-blocking background execution in Ruby script

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

You easily do this using a thread.

puts 'hello'

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

puts 'there'
``
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading