Rails 2.2: ActiveRecord in thread doesn't run if action has completed

I have some callback code that submits data over the net, gets an id
back and should write it to DB.

This takes a few seconds. I want to run it asynchronously, without
slowing down the request/response cycle. I would like to avoid a
worker/queue system if possible, to keep things simple.

I eventually want it in an observer, but I’m currently trying it out
right in a controller. If I do this:

def some_action

Thread.new {
Thread.abort_on_exception = true
logger.debug “!! 1”
sleep 5
logger.debug “!! 2”
sleep 5
logger.debug “!! Posts: #{Post.count}”
sleep 5
logger.debug “!! 3”
}
render :text => “foo”
end

Then visiting that page will log 1 and 2, but nothing else. 2 can log
after the action completes:

Completed in 4734ms (View: 4619, DB: 36) | 200 OK [http://
mysite.dev/]
!! 2

If the thread is this instead:

Thread.new {
  Thread.abort_on_exception = true
  logger.debug "!! 1"
  logger.debug "!! 2"
  logger.debug "!! Posts: #{Post.count}"
  sleep 10
  logger.debug "!! 3"
}

so Post.count runs before the action completes, then it works fine,
and 3 can output after the action completes:


!! Posts: 33

Completed in 5078ms (View: 4940, DB: 29) | 200 OK [http://
mysite.dev/]
!! 3

So basically, it seems that a thread in a controller action can run
after the action completes, but ActiveRecord can’t.

Is this an inherent limitation? Can I configure my way around it? I
was hoping 2.2 connection pools would mean this would work, but I
guess not.

I’ve looked at GitHub - imedo/background: deprecated - Please use successor project background_lite and
GitHub - tra/spawn: Placeholder for the repo previously known as spawn
but had issues with both, so I thought I’d try to figure it out with a
simple Thread for now.

On Oct 25, 9:19 am, Henrik N [email protected] wrote:

Aha! Changing
config.cache_classes = true
to
config.cache_classes = false
in config/environments/development.rb fixed this.

Oops. The other way around, of course. Changing from false to true.

On Oct 25, 1:08 am, Henrik N [email protected] wrote:

So basically, it seems that a thread in a controller action can run
after the action completes, but ActiveRecord can’t.

Is this an inherent limitation? Can I configure my way around it? I
was hoping 2.2 connection pools would mean this would work, but I
guess not.

Aha! Changing
config.cache_classes = true
to
config.cache_classes = false
in config/environments/development.rb fixed this. So I expect the
class was reloaded, messing up the connection.