EventMachine Timer for each open connection

40 views Asked by At

We have a need to have EventMachine servers 'ping' the clients that are connected to them every few seconds.

EventMachine.run do
  config.each do |instance|
    case instance[:type]
    when 'A'
      EventMachine.start_server instance[:hostname], instance[:port_num], AServer, instance
      puts "#{Time.now.utc} :: A #{instance[:hostname]}/#{instance[:port_num]} :: Initialize"
    when 'B'
      EventMachine.start_server instance[:hostname], instance[:port_num], BServer, instance
      puts "#{Time.now.utc} :: B #{instance[:hostname]}/#{instance[:port_num]} :: Initialize"
    end
  end

For clients connecting to BServer, we want to send them a single character every 10 seconds -- how can I instantiate a Timer for each BServer that is started?

1

There are 1 answers

0
Michael On

OK turns out it was easier than I thought. In the post_init method of the implementation of my BServer I add this:

EM.add_periodic_timer(10) do
  send_char('A')
end