Rails: Thread won't affect database unless joined to main Thread

Posted by hatboysam on Stack Overflow See other posts from Stack Overflow or by hatboysam
Published on 2012-09-16T03:18:05Z Indexed on 2012/09/16 3:37 UTC
Read the original article Hit count: 171

I have a background operation I would like to occur every 20 seconds in Rails given that some condition is true. It kicked off when a certain controller route is hit, and it looks like this

def startProcess
    argId = self.id
    t = Thread.new do
        while (Argument.isRunning(argId)) do
            Argument.update(argId)
            Argument.markVotes(argId)
            puts "Thread ran"
            sleep 20
        end
    end
end

However, this code does absolutely nothing to my database unless I call "t.join" in which case my whole server is blocked for a long time (but it works).

Why can't the read commit ActiveRecords without being joined to the main thread? The thread calls methods that look something like

def sample
  model = Model.new()
  model.save()
end

but the models are not saved to the DB unless the thread is joined to the main thread. Why is this? I have been banging my head about this for hours.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby