We've already seen how to execute asynchronous background tasks in TorqueBox, but what if our application needs a persistent background daemon that's neither a scheduled job nor a background task? Luckily, TorqueBox has a solution for this as well.
TorqueBox Services are a really cool way to replace the external daemons that Ruby applications seem to accumulate over time with something that's integrated with the rest of the application. Download the latest developer build, give them a try, and I think you'll agree that TorqueBox Services are far easier than managing an external process.
To learn about TorqueBox Services, we'll create an IRC bot that runs as a Service. Portions of the sample application will be displayed inline and the entire source is available at https://github.com/torquebox/torquebox-irc-bot.
Add a Service to Our Application
Adding a Service only requires creating a services.yml and a class with initialize, start, and stop methods. We're going to start with a basic Rails 3 application but TorqueBox Services also work with Rails 2 and Rack applications.
First let's add a config/services.yml containing the class of our Service, IrcBotService, and the initialization parameters it needs.
IrcBotService:
nick: torquebox_bot
server: irc.freenode.net
port: 6667
channel: '#torquebox'
Then let's add the referenced IrcBotService class under a new app/services/ folder.
class IrcBotService
def initialize(options={})
@nick = options['nick']
@server = options['server']
@port = options['port']
@channel = options['channel']
end
def start
@bot = configure_bot
# Start the IRC bot in a separate thread
@bot_thread = Thread.new { @bot.connect }
end
def stop
# Disconnect from IRC
@bot.quit
# Wait for the bot thread to exit
@bot_thread.join
end
end
The start method of IrcBotService gets called when our application is
deployed. An EventMachine event loop gets started inside
@bot.connect so we execute that in a separate thread since the start
method should execute quickly and not block.
When our application is undeployed the stop method gets called so we can cleanly disconnect from IRC.
That's all the code that's required to get rid of those Ruby daemons and manage them alongside your web application in TorqueBox. Stay tuned for futures article where we'll cluster our service and connect a web application for near-real-time display of messages.