1

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?

1
  • "execute some code in the background and exit immediately" – if you exit (as in terminate the Ruby script / process), your code won't run anymore. For background tasks in Rails, have a look at Active Job or Sidekiq Commented Jan 13, 2023 at 18:41

1 Answer 1

2

You easily do this using a thread.

puts 'hello'

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

puts 'there'
``
Sign up to request clarification or add additional context in comments.

1 Comment

Note that without join the sub thread will be killed as soon as the main thread printed "there". It doesn't keep running on its own.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.