# Refresh Machine

**URL:** <https://www.ruby-forum.com/t/refresh-machine/226022>\
**Category:** Ruby\
**Created:** [August 13, 2008, 5:45pm UTC](https://www.ruby-forum.com/t/refresh-machine/226022 "2008-08-13T17:45:01Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Pablo\_Lorenzzoni](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/db5fbb/32.png) [@Pablo\_Lorenzzoni](https://www.ruby-forum.com/u/Pablo_Lorenzzoni)\
**Post date:** [August 13, 2008, 5:45pm UTC](https://www.ruby-forum.com/t/refresh-machine/226022/1 "2008-08-13T17:45:01Z")

</div>

Hello,

Recently I had to deal with external data sources that had to be  
refresh every now and then. Instead of using an infinite loop inside a  
thread for every object, I used Queue to create a “Refresh Machine”.  
Below is the code… my questions are: can it be improved? is there  
another way to do the same?

Thanks

Pablo

require ‘thread’  
class RefreshMachine

attr\_accessor :wait

def initialize(wait = false)  
@wait = wait  
@killall = false  
@queue = Queue.new  
@removed = Array.new  
@thread = Thread.new do  
loop do  
( @removed.clear; @queue.clear; @killall = false ) if @killall  
next if @queue.empty?  
object, last\_refresh, thread = @queue.deq

```
     # Helps the garbage collection
     thread = nil if (! thread.nil?) and (! thread.alive?)

     # Three things can happen with a dequeued object
     if (Time.now < (last_refresh + object.refresh)) or
        (! thread.nil? and @wait)
       # First: It's too early to refresh it or we still have
       # a refresh thread running and have to 'wait', so we
       # just put it back in the queue
       @queue.enq [object, last_refresh, thread]
     else
       if @removed.include?(object)
         # Second: We have a "remove request" for it, so we
         # delete the request and avoid queueing it again
         @removed.delete(object)
       else
         # Third: It's time to refresh it, so we
         # call do_refresh and put it back in the queue
         add(object)
       end
     end
   end
 end

```

end

def add(object)  
@queue.enq [object, Time.now, Thread.new { object.do\_refresh }]  
end

def del(object)  
@removed \<\< object unless @removed.include?(object)  
end

def killall  
@killall = true  
end

end # of class RefreshMachine

---

<div class="post-metadata">

**Author:** ![Pablo\_Lorenzzoni](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/db5fbb/32.png) [@Pablo\_Lorenzzoni](https://www.ruby-forum.com/u/Pablo_Lorenzzoni)\
**Post date:** [August 13, 2008, 9:07pm UTC](https://www.ruby-forum.com/t/refresh-machine/226022/2 "2008-08-13T21:07:12Z")

</div>

Great code. You forgot to mention that “object” should implement  
#refresh and #do\_refresh. The second is easy to understand (something  
that does the refresh), but the first I am not sure… is it a time  
interval?
