---
title: "Rails3利用whenever gem调度发送邮件"
author: "myrev"
date: "2010-12-01T10:42:53Z"
tags: []
categories: ["编程语言"]
slug: "rails3-whenever-gem"
draft: false
lastmod: "2010-12-01T10:42:53Z"
id: 830164
url: "https://myrev.iteye.com/blog/830164"
---

1\. Install

```
$ gem install whenever
```

Or with Bundler in your Gemfile.

```
gem 'whenever', :require => false
```

2\. Getting Started

```
$ cd /my/rails/app
$ wheneverize .
```

This will create an initial "**config/schedule.rb**" file you.

config/schedule.rb

\# Learn more: http://github.com/javan/whenever

set :output, "#{path}/log/whenever.log"

every 15.minutes do

  rake "send\_emails"

end

 

3\. Rake Tasks

desc "send emails"

task :send\_emails do

  command = "ar\_sendmail\_rails3 -o -e #{Rails.env}"

  \`#{command}\`

end

4\. Command

### The `whenever` command

```
$ cd /my/rails/app
$ whenever
```

This will simply show you your schedule.rb file converted to cron syntax. It does not read or write your crontab file. Run `whenever --help` for a complete list of options.

Usage: whenever \[options]

    -i \[identifier],                 Default: full path to schedule.rb file

        --update-crontab

    -w, --write-crontab \[identifier] Default: full path to schedule.rb file

    -c, --clear-crontab \[identifier]

    -s, --set \[variables]            Example: --set environment=staging&path=/my/sweet/path

    -f, --load-file \[schedule file]  Default: config/schedule.rb

    -u, --user \[user]                Default: current user

    -k, --cut \[lines]                Cut lines from the top of the cronfile

    -v, --version

5\. Add cron job

$ cd /my/rails/app  
$ whenever -s environment=qa -w AC

6\. Update cron job

$ cd /my/rails/app  
$ whenever -i AC

7\. Clear cron job

$ cd /my/rails/app  
$ whenever -c AC

8\. Capistrano

namespace :deploy do

...  

desc "Stop the existing cron job"

  task :stop\_cron, :roles=&gt;:app do

    run("crontab -r")

  end

  desc "Update the crontab file"

  task :update\_crontab, :roles =&gt; :db do

    run "cd #{current\_path} && whenever --set environment=#{rails\_env} --update-crontab #{application}"

  end

....

end

After Task

after "deploy:symlink","deploy:update\_crontab"

9\. Tips

If you use RVM, you should install it on system root path or make a soft link to rake. Maybe whenever can't find rake in /usr/bin/.

More: [https://github.com/javan/whenever](https://github.com/javan/whenever)