Last Updated: February 25, 2016
·
15.83K
· jeroenj

Background daemons in your Rails app with the daemons gem

In this example I'll show you how you can simply set up a mailman daemon with the daemons gem.

First you'll need to create a mailman script which will receive and process your emails:

#!/usr/bin/env ruby

require 'rubygems'
require 'bundler/setup'
require 'mailman'

require "#{File.dirname __FILE__}/../config/environment"

Mailman.config.pop3 = {} # server details go here

Mailman::Application.run do
  default do
    # process email
  end
end

We'll create that in script/mailman_server. Don't forget to run chmod +x on that file in order to be able to run the script.

Next we'll have to set up our daemon. We also place this in script/mailman_daemon. Once again, don't forget to run chmod +x on it.

#!/usr/bin/env ruby

require 'rubygems'
require 'bundler/setup'
require 'daemons'

Daemons.run 'script/mailman_server'

Now you can run the following commands on your daemon:

bundle exec script/mailman_daemon start   # to start your daemon
bundle exec script/mailman_daemon stop    # to start your daemon
bundle exec script/mailman_daemon restart # to restart your daemon

Everything is pretty straight forward.

You can easily add this to your deployment setup with Capistrano too. For that I'd advise you to use Capo which is a great tool to manage your Capistrano recipes. If you have it set up in your application you can add the daemons recipe by running capo add ruby_daemons. You'll just need to set the daemons variable to add it for mailman in your config/deploy.rb like this: set :daemons, [:mailman].

More information about setting up mailman can be found here. This also covers the basic setup with the daemons gem.

4 Responses
Add your response

Unfortunately error appears when require "#{File.dirname FILE}/../config/environment"

over 1 year ago ·

Which ruby version are you using?
Do you have a file in ../config/environment?

over 1 year ago ·

If someone starts mailman in the rails environment the pid should created in the tmp/pids directory. Therefor I set the dir in the script/mailman_daemon file like this:

Daemons.run 'script/mailman_server', 
  dir: File.expand_path(File.join(File.dirname(__FILE__), '..', 'tmp', 'pids')), 
  dir_mode: :normal

This is important for restarting mailman_daemon together with capistrano.

over 1 year ago ·

Indeed. You can even simplify that a bit bu using this: dir: 'tmp/pids',

over 1 year ago ·