Compare commits

..

No commits in common. "master" and "rails3" have entirely different histories.

30 changed files with 525 additions and 854 deletions

1
.gitignore vendored
View File

@ -2,4 +2,3 @@
pkg
doc
.*.sw[a-z]
Gemfile.lock

View File

@ -1,7 +0,0 @@
rvm:
- 1.8.7
- 1.9.2
- ree
- rbx
- rbx-2.0
- jruby

View File

@ -1,66 +1,11 @@
### 0.6.9 / June 8th, 2011
* Use mojombo's chronic, it's active again. [Javan Makhmali]
### 0.6.8 / May 24th, 2011
* Convert most shortcuts to seconds. every :day -> every 1.day. #129 [Javan Makhmali]
* Allow commas in raw cron syntax. #130 [Marco Bergantin, Javan Makhmali]
* Output no update message as comments. #135 [Javan Makhmali]
* require 'thread' to support Rubygems >= 1.6.0. #132 [Javan Makhmali]
### 0.6.7 / March 23rd, 2011
* Fix issue with comment block being corrupted during subsequent insertion of duplicate entries to the crontab. #123 [Jeremy (@lingmann)]
* Removed -i from default job template. #118 [Javan Makhmali]
### 0.6.6 / March 8th, 2011
* Fix unclosed identifier bug. #119 [Javan Makhmali]
### 0.6.5 / March 8th, 2011
* Preserve whitespace at the end of crontab file. #95 [Rich Meyers]
* Setting nil or blank environment variables now properly formats output. [T.J. VanSlyke]
* Allow raw cron sytax, added -i to bash job template, general cleanup. [Javan Makhmali]
### 0.6.2 / October 26th, 2010
* --clear-crontab option completely removes entries. #63 [Javan Makhmali]
* Set default :environment and :path earlier in the new setup.rb (formerly job_types/default.rb). [Javan Makhmali]
* Converted README and CHANGELOG to markdown. [Javan Makhmali]
### 0.6.1 / October 20th, 2010
* Detect script/rails file and change runner to Rails 3 style if found. [Javan Makhmali]
* Created a new :job_template system that can be applied to all commands. Wraps all in bash -l -c 'command..' by default now for better RVM support. Stopped automatically setting the PATH too. [Javan Makhmali]
* Added a built-in Capistrano recipe. [Javan Makhmali]
### 0.5.3 / September 24th, 2010
== 0.5.3 / September 24th, 2010
* Better regexes for replacing Whenever blocks in the crontab. #45 [Javan Makhmali]
* Preserving backslashes when updating existing crontab. #82 [Javan Makhmali]
### 0.5.2 / September 15th, 2010
== 0.5.2 / September 15th, 2010
* Quotes automatically escaped in jobs. [Jay Adkisson]
@ -71,7 +16,7 @@
* Lots of internal reorganizing; tests broken into unit and functional. [Javan Makhmali]
### 0.5.0 / June 28th, 2010
== 0.5.0 / June 28th, 2010
* New job_type API for writing custom jobs. Internals use this to define command, runner, and rake. [Javan Makhmali - inspired by idlefingers (Damien)]
@ -80,7 +25,7 @@
* --clear option to remove crontab entries for a specific [identifier]. [mraidel (Michael Raidel)]
### 0.4.2 / April 26th, 2010
== 0.4.2 / April 26th, 2010
* runners now cd into the app's directory and then execute. [Michael Guterl]
@ -91,49 +36,49 @@
* bugfix: comparison Time with 0 failed. #32 [Dan Hixon]
### 0.4.1 / November 30th, 2009
== 0.4.1 / November 30th, 2009
* exit(0) instead of just exit to make JRuby happy. [Elan Meng]
* Fixed activesupport deprecation warning by requiring active_support. #37 [Andrew Nesbitt]
### 0.4.0 / October 20th, 2009
== 0.4.0 / October 20th, 2009
* New output option replaces the old cron_log option for output redirection and is much more flexible. #31 [Peer Allan]
* Reorganized the lib files (http://weblog.rubyonrails.org/2009/9/1/gem-packaging-best-practices) and switched to Jeweler from Echoe.
### 0.3.7 / September 4th, 2009
== 0.3.7 / September 4th, 2009
* No longer tries (and fails) to combine @shortcut jobs. #20 [Javan Makhmali]
### 0.3.6 / June 15th, 2009
== 0.3.6 / June 15th, 2009
* Setting a PATH in the crontab automatically based on the user's PATH. [Javan Makhmali]
### 0.3.5 / June 13th, 2009
== 0.3.5 / June 13th, 2009
* Added ability to accept lists of every's and at's and intelligently group them. (ex: every 'monday, wednesday', :at => ['3pm', '6am']). [Sam Ruby]
* Fixed issue with new lines. #18 [Javan Makhmali]
### 0.3.1 / June 25th, 2009
== 0.3.1 / June 25th, 2009
* Removed activesupport gem dependency. #1 [Javan Makhmali]
* Switched to numeric days of the week for Solaris support (and probably others). #8 [Roger Ertesvåg]
### 0.3.0 / June 2nd, 2009
== 0.3.0 / June 2nd, 2009
* Added ability to set variables on the fly from the command line (ex: whenever --set environment=staging). [Javan Makhmali]
### 0.2.2 / April 30th, 2009
== 0.2.2 / April 30th, 2009
* Days of week jobs can now accept an :at directive (ex: every :monday, :at => '5pm'). [David Eisinger]
@ -142,22 +87,22 @@
* Raising an exception if someone tries to specify an :at with a cron shortcut (:day, :reboot, etc) so there are no false hopes. [Javan Makhmali]
### 0.1.7 / March 5th, 2009
== 0.1.7 / March 5th, 2009
* Added ability to update the crontab file non-destuctively instead of only overwriting it. [Javan Makhmali -- Inspired by code submitted individually from: Tien Dung (tiendung), Tom Lea (cwninja), Kyle Maxwell (fizx), and Andrew Timberlake (andrewtimberlake) on github]
### 0.1.5 / February 19th, 2009
== 0.1.5 / February 19th, 2009
* Fixed load path so Whenever's files don't conflict with anything in Rails. Thanks Ryan Koopmans. [Javan Makhmali]
### 0.1.4 / February 17th, 2009
== 0.1.4 / February 17th, 2009
* Added --load-file and --user opts to whenever binary. [Javan Makhmali]
### 0.1.3 / February 16th, 2009
== 0.1.3 / February 16th, 2009
* Added 'rake' helper for defining scheduled rake tasks. [Javan Makhmali]
@ -170,6 +115,6 @@
* Requiring specific gem versions: Chronic >=0.2.3 and activesupport >= 1.3.0 [Javan Makhmali]
### 0.1.0 / February 15th, 2009
== 0.1.0 / February 15th, 2009
* Initial release [Javan Makhmali]

View File

@ -1,4 +0,0 @@
source "http://rubygems.org"
# Specify your gem's dependencies in newever.gemspec
gemspec

22
LICENSE
View File

@ -1,22 +0,0 @@
Copyright (c) 2011 Javan Makhmali
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

163
README.md
View File

@ -1,163 +0,0 @@
### Introduction
Whenever is a Ruby gem that provides a clear syntax for writing and deploying cron jobs.
### Installation
```sh
$ gem install whenever
```
Or with Bundler in your Gemfile.
```ruby
gem 'whenever', :require => false
```
### Getting started
```sh
$ cd /apps/my-great-project
$ wheneverize .
```
This will create an initial `config/schedule.rb` file you.
### Example schedule.rb file
```ruby
every 3.hours do
runner "MyModel.some_process"
rake "my:rake:task"
command "/usr/bin/my_great_command"
end
every 1.day, :at => '4:30 am' do
runner "MyModel.task_to_run_at_four_thirty_in_the_morning"
end
every :hour do # Many shortcuts available: :hour, :day, :month, :year, :reboot
runner "SomeModel.ladeeda"
end
every :sunday, :at => '12pm' do # Use any day of the week or :weekend, :weekday
runner "Task.do_something_great"
end
every '0 0 27-31 * *' do
command "echo 'you can use raw cron syntax too'"
end
```
### Define your own job types
Whenever ships with three pre-defined job types: command, runner, and rake. You can define your own with `job_type`.
For example:
```ruby
job_type :awesome, '/usr/local/bin/awesome :task :fun_level'
every 2.hours do
awesome "party", :fun_level => "extreme"
end
```
Would run `/usr/local/bin/awesome party extreme` every two hours. `:task` is always replaced with the first argument, and any additional `:whatevers` are replaced with the options passed in or by variables that have been defined with `set`.
The default job types that ship with Whenever are defined like so:
```ruby
job_type :command, ":task :output"
job_type :rake, "cd :path && RAILS_ENV=:environment rake :task :output"
job_type :runner, "cd :path && script/runner -e :environment ':task' :output"
```
If a `script/rails` file is detected (like in a Rails 3 app), runner will be defined to fit:
```ruby
job_type :runner, "cd :path && script/rails runner -e :environment ':task' :output"
```
If a `:path` is not set it will default to the directory in which `whenever` was executed. `:environment` will default to 'production'. `:output` will be replaced with your output redirection settings which you can read more about here: <http://github.com/javan/whenever/wiki/Output-redirection-aka-logging-your-cron-jobs>
All jobs are by default run with `bash -l -c 'command...'`. Among other things, this allows your cron jobs to play nice with RVM by loading the entire environment instead of cron's somewhat limited environment. Read more: <http://blog.scoutapp.com/articles/2010/09/07/rvm-and-cron-in-production>
You can change this by setting your own `:job_template`.
```ruby
set :job_template, "bash -l -c ':job'"
```
Or set the job_template to nil to have your jobs execute normally.
```ruby
set :job_template, nil
```
### Capistrano integration
Use the built-in Capistrano recipe for easy crontab updates with deploys.
In your "config/deploy.rb" file:
```ruby
require "whenever/capistrano"
```
Take a look at the recipe for options you can set. <http://github.com/javan/whenever/blob/master/lib/whenever/capistrano.rb>
For example, if you're using bundler do this:
```ruby
set :whenever_command, "bundle exec whenever"
require "whenever/capistrano"
```
If you are using different environments (such as staging, production), then you may want to do this:
```ruby
set :whenever_environment, defer { stage }
require "whenever/capistrano"
```
The capistrano variable `:stage` should be the one holding your environment name. This will make the correct `:environment` available in your `schedule.rb`.
### RVM Integration
If your production environment uses RVM (Ruby Version Manager) you will run into a gotcha that causes your cron jobs to hang. This is not directly related to Whenever, and can be tricky to debug. Your .rvmrc files must be trusted or else the cron jobs will hang waiting for the file to be trusted. A solution is to disable the prompt by adding this line to your user rvm file in `~/.rvmrc`
`rvm_trust_rvmrcs_flag=1`
This tells rvm to trust all rvmrc files, which is documented here: http://wayneeseguin.beginrescueend.com/2010/08/22/ruby-environment-version-manager-rvm-1-0-0/
### The `whenever` command
```sh
$ cd /apps/my-great-project
$ 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.
### Credit
Whenever was created for use at Inkling (<http://inklingmarkets.com>). Their take on it: <http://blog.inklingmarkets.com/2009/02/whenever-easy-way-to-do-cron-jobs-from.html>
Thanks to all the contributors who have made it even better: <http://github.com/javan/whenever/contributors>
### Discussion / Feedback / Issues / Bugs
For general discussion and questions, please use the google group: <http://groups.google.com/group/whenever-gem>
If you've found a genuine bug or issue, please use the Issues section on github: <http://github.com/javan/whenever/issues>
Ryan Bates created a great Railscast about Whenever: <http://railscasts.com/episodes/164-cron-in-ruby>
It's a little bit dated now, but remains a good introduction.
----
Compatible with Ruby 1.8.7-1.9.2, JRuby, and Rubinius. [![Build Status](https://secure.travis-ci.org/javan/whenever.png)](http://travis-ci.org/javan/whenever)
----
Copyright &copy; 2011 Javan Makhmali

127
README.rdoc Normal file
View File

@ -0,0 +1,127 @@
== Introduction
Whenever is a Ruby gem that provides a clear syntax for defining cron jobs. It outputs valid cron syntax and can even write your crontab file for you. It is designed to work well with Rails applications and can be deployed with Capistrano. Whenever works fine independently as well.
Ryan Bates created a great Railscast about Whenever: http://railscasts.com/episodes/164-cron-in-ruby
Discussion: http://groups.google.com/group/whenever-gem
== Installation
$ sudo gem install whenever
== Getting started
$ cd /my/rails/app
$ wheneverize .
This will create an initial "config/schedule.rb" file you.
== Example schedule.rb file
every 3.hours do
runner "MyModel.some_process"
rake "my:rake:task"
command "/usr/bin/my_great_command"
end
every 1.day, :at => '4:30 am' do
runner "MyModel.task_to_run_at_four_thirty_in_the_morning"
end
every :hour do # Many shortcuts available: :hour, :day, :month, :year, :reboot
runner "SomeModel.ladeeda"
end
every :sunday, :at => '12pm' do # Use any day of the week or :weekend, :weekday
runner "Task.do_something_great"
end
More examples on the wiki: http://wiki.github.com/javan/whenever/instructions-and-examples
== Define your own job types
Whenever ships with three pre-defined job types: command, runner, and rake. You can define your own with <code>job_type</code>.
For example:
job_type :awesome, '/usr/local/bin/awesome :task :fun_level'
every 2.hours do
awesome "party", :fun_level => "extreme"
end
Would run <code>/usr/local/bin/awesome party extreme</code> every two hours. <code>:task</code> is always replaced with the first argument, and any additional <code>:whatevers</code> are replaced with the options passed in or by variables that have been defined with <code>set</code>.
The default job types that ship with Whenever are defined like so:
job_type :command, ":task"
job_type :runner, "cd :path && script/runner -e :environment ':task'"
job_type :rake, "cd :path && RAILS_ENV=:environment /usr/bin/env rake :task"
If a <code>:path</code> is not set it will default to the directory in which <code>whenever</code> was executed. <code>:environment</code> will default to 'production'.
== Cron output
$ cd /my/rails/app
$ whenever
And you'll see your schedule.rb converted to cron sytax. Note: running `whenever' with no options does not display your current crontab file, it simply shows you the output of converting your schedule.rb file.
== Capistrano integration
In your "config/deploy.rb" file do something like:
after "deploy:symlink", "deploy:update_crontab"
namespace :deploy do
desc "Update the crontab file"
task :update_crontab, :roles => :db do
run "cd #{release_path} && whenever --update-crontab #{application}"
end
end
This will update your crontab file, leaving any existing entries unharmed. When using the <code>--update-crontab</code> option, Whenever will only update the entries in your crontab file related to the current schedule.rb file. You can replace the <code>#{application}</code> with any identifying string you'd like. You can have any number of apps deploy to the same crontab file peacefully given they each use a different identifier.
If you wish to simply overwrite your crontab file each time you deploy, use the <code>--write-crontab</code> option. This is ideal if you are only working with one app and every crontab entry is contained in a single schedule.rb file.
By mixing and matching the <code>--load-file</code> and <code>--user</code> options with your various :roles in Capistrano it is entirely possible to deploy different crontab schedules under different users to all your various servers. Get creative!
If you want to override a variable (like your environment) at the time of deployment you can do so with the <code>--set</code> option: http://wiki.github.com/javan/whenever/setting-variables-on-the-fly
== Credit
Whenever was created for use at Inkling (http://inklingmarkets.com) where I work. Their take on it: http://blog.inklingmarkets.com/2009/02/whenever-easy-way-to-do-cron-jobs-from.html
While building Whenever, I learned a lot by digging through the source code of Capistrano - http://github.com/jamis/capistrano
== Discussion / Feedback / Issues / Bugs
For general discussion and questions, please use the google group: http://groups.google.com/group/whenever-gem
If you've found a genuine bug or issue, please use the Issues section on github: http://github.com/javan/whenever/issues
== License
Copyright (c) 2009+ Javan Makhmali
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,11 +1,35 @@
require 'bundler'
Bundler::GemHelper.install_tasks
require 'rubygems'
require 'rake'
require File.expand_path(File.dirname(__FILE__) + "/lib/whenever/version")
begin
require 'jeweler'
Jeweler::Tasks.new do |gemspec|
gemspec.name = "whenever"
gemspec.version = Whenever::VERSION
gemspec.summary = "Clean ruby syntax for defining and deploying messy cron jobs."
gemspec.description = "Clean ruby syntax for defining and deploying messy cron jobs."
gemspec.email = "javan@javan.us"
gemspec.homepage = "http://github.com/javan/whenever"
gemspec.authors = ["Javan Makhmali"]
gemspec.add_dependency 'aaronh-chronic', '>= 0.3.9'
gemspec.add_dependency 'activesupport', '>= 2.3.4'
gemspec.add_development_dependency 'shoulda', '>= 2.1.1'
gemspec.add_development_dependency 'mocha', '>= 0.9.5'
end
Jeweler::GemcutterTasks.new
rescue LoadError
puts "Jeweler not available. Install it with: sudo gem install jeweler -s http://gemcutter.org"
end
require 'rake/testtask'
Rake::TestTask.new(:test) do |test|
test.libs << 'lib' << 'test'
test.pattern = 'test/{functional,unit}/**/*_test.rb'
test.verbose = true
end
test.libs << 'lib' << 'test'
test.pattern = 'test/{functional,unit}/**/*_test.rb'
test.verbose = true
end
task :test => :check_dependencies
task :default => :test

3
bin/whenever Executable file → Normal file
View File

@ -3,7 +3,6 @@
require 'rubygems'
require 'optparse'
require 'whenever'
require 'whenever/version'
options = {}
@ -21,7 +20,7 @@ OptionParser.new do |opts|
options[:clear] = true
options[:identifier] = identifier if identifier
end
opts.on('-s', '--set [variables]', 'Example: --set \'environment=staging&path=/my/sweet/path\'') do |set|
opts.on('-s', '--set [variables]', 'Example: --set environment=staging&path=/my/sweet/path') do |set|
options[:set] = set if set
end
opts.on('-f', '--load-file [schedule file]', 'Default: config/schedule.rb') do |file|

19
bin/wheneverize Executable file → Normal file
View File

@ -17,16 +17,17 @@ OptionParser.new do |opts|
end
end
unless ARGV.empty?
if !File.exists?(ARGV.first)
abort "`#{ARGV.first}' does not exist."
elsif !File.directory?(ARGV.first)
abort "`#{ARGV.first}' is not a directory."
elsif ARGV.length > 1
abort "Too many arguments; please specify only the directory to wheneverize."
end
if ARGV.empty?
abort "Please specify the directory to wheneverize, e.g. `#{File.basename($0)} .'"
elsif !File.exists?(ARGV.first)
abort "`#{ARGV.first}' does not exist."
elsif !File.directory?(ARGV.first)
abort "`#{ARGV.first}' is not a directory."
elsif ARGV.length > 1
abort "Too many arguments; please specify only the directory to wheneverize."
end
content = <<-FILE
# Use this file to easily define all of your cron jobs.
#
@ -51,7 +52,7 @@ content = <<-FILE
FILE
file = 'config/schedule.rb'
base = ARGV.empty? ? '.' : ARGV.shift
base = ARGV.shift
file = File.join(base, file)
if File.exists?(file)

View File

@ -1,30 +1,10 @@
require 'chronic'
require 'active_support/all'
require 'thread'
module Whenever
autoload :JobList, 'whenever/job_list'
autoload :Job, 'whenever/job'
autoload :CommandLine, 'whenever/command_line'
module Output
autoload :Cron, 'whenever/cron'
autoload :Redirection, 'whenever/output_redirection'
end
def self.cron(options)
Whenever::JobList.new(options).generate_cron_output
end
def self.path
Dir.pwd
end
def self.rails3?
File.exists?(File.join(path, 'script', 'rails'))
end
def self.bundler?
File.exists?(File.join(path, 'Gemfile'))
end
end
require 'whenever/base'
require 'whenever/job_list'
require 'whenever/job'
require 'whenever/cron'
require 'whenever/output_redirection'
require 'whenever/command_line'
require 'whenever/version'

11
lib/whenever/base.rb Normal file
View File

@ -0,0 +1,11 @@
module Whenever
def self.cron(options)
Whenever::JobList.new(options).generate_cron_output
end
def self.path
Dir.pwd
end
end

View File

@ -1,62 +0,0 @@
Capistrano::Configuration.instance(:must_exist).load do
_cset(:whenever_roles) { :db }
_cset(:whenever_command) { "whenever" }
_cset(:whenever_identifier) { fetch :application }
_cset(:whenever_environment) { fetch :rails_env, "production" }
_cset(:whenever_update_flags) { "--update-crontab #{fetch :whenever_identifier} --set environment=#{fetch :whenever_environment}" }
_cset(:whenever_clear_flags) { "--clear-crontab #{fetch :whenever_identifier}" }
# Disable cron jobs at the begining of a deploy.
after "deploy:update_code", "whenever:clear_crontab"
# Write the new cron jobs near the end.
after "deploy:symlink", "whenever:update_crontab"
# If anything goes wrong, undo.
after "deploy:rollback", "whenever:update_crontab"
namespace :whenever do
desc <<-DESC
Update application's crontab entries using Whenever. You can configure \
the command used to invoke Whenever by setting the :whenever_command \
variable, which can be used with Bundler to set the command to \
"bundle exec whenever". You can configure the identifier used by setting \
the :whenever_identifier variable, which defaults to the same value configured \
for the :application variable. You can configure the environment by setting \
the :whenever_environment variable, which defaults to the same value \
configured for the :rails_env variable which itself defaults to "production". \
Finally, you can completely override all arguments to the Whenever command \
by setting the :whenever_update_flags variable. Additionally you can configure \
which servers the crontab is updated on by setting the :whenever_roles variable.
DESC
task :update_crontab do
options = { :roles => fetch(:whenever_roles) }
if find_servers(options).any?
on_rollback do
if fetch :previous_release
run "cd #{fetch :previous_release} && #{fetch :whenever_command} #{fetch :whenever_update_flags}", options
else
run "cd #{fetch :release_path} && #{fetch :whenever_command} #{fetch :whenever_clear_flags}", options
end
end
run "cd #{fetch :current_path} && #{fetch :whenever_command} #{fetch :whenever_update_flags}", options
end
end
desc <<-DESC
Clear application's crontab entries using Whenever. You can configure \
the command used to invoke Whenever by setting the :whenever_command \
variable, which can be used with Bundler to set the command to \
"bundle exec whenever". You can configure the identifier used by setting \
the :whenever_identifier variable, which defaults to the same value configured \
for the :application variable. Finally, you can completely override all \
arguments to the Whenever command by setting the :whenever_clear_flags variable. \
Additionally you can configure which servers the crontab is cleared on by setting \
the :whenever_roles variable.
DESC
task :clear_crontab do
options = { :roles => whenever_roles }
run "cd #{fetch :release_path} && #{fetch :whenever_command} #{fetch :whenever_clear_flags}", options if find_servers(options).any?
end
end
end

View File

@ -3,6 +3,7 @@ require 'tempfile'
module Whenever
class CommandLine
def self.execute(options={})
new(options).run
end
@ -29,6 +30,7 @@ module Whenever
exit(1)
end
@options[:cut] = @options[:cut].to_i
end
def run
@ -38,8 +40,6 @@ module Whenever
write_crontab(whenever_cron)
else
puts Whenever.cron(@options)
puts "## [message] Above is your schedule file converted to cron syntax; your crontab file was not updated."
puts "## [message] Run `whenever --help' for more options."
exit(0)
end
end
@ -51,90 +51,62 @@ module Whenever
end
def whenever_cron
return '' if @options[:clear]
@whenever_cron ||= [comment_open, Whenever.cron(@options), comment_close].compact.join("\n") + "\n"
@whenever_cron ||= [comment_open, (Whenever.cron(@options) unless @options[:clear]), comment_close].compact.join("\n") + "\n"
end
def read_crontab
return @current_crontab if @current_crontab
command_results = (
if !stdin.tty?
stdin.read
else
command = ['crontab -l']
command << "-u #{@options[:user]}" if @options[:user]
result = %x[#{command.join(' ')} 2> /dev/null]
$?.exitstatus.zero? ? result : ''
end
)
@current_crontab = prepare(command_results)
command = ['crontab -l']
command << "-u #{@options[:user]}" if @options[:user]
command_results = %x[#{command.join(' ')} 2> /dev/null]
@current_crontab = $?.exitstatus.zero? ? prepare(command_results) : ''
end
def write_crontab(contents)
target_fh = (
if !stdin.tty?
stdout
else
File.open(Tempfile.new('whenever_tmp_cron').path, File::WRONLY | File::APPEND)
end
)
target_fh << contents
target_fh.close
tmp_cron_file = Tempfile.new('whenever_tmp_cron').path
File.open(tmp_cron_file, File::WRONLY | File::APPEND) do |file|
file << contents
end
if !stdin.tty?
command = ['crontab']
command << "-u #{@options[:user]}" if @options[:user]
command << tmp_cron_file
if system(command.join(' '))
action = 'written' if @options[:write]
action = 'updated' if @options[:update]
puts "[write] crontab file #{action}"
exit(0)
else
command = ['crontab']
command << "-u #{@options[:user]}" if @options[:user]
command << target_file
if system(command.join(' '))
action = 'written' if @options[:write]
action = 'updated' if @options[:update]
puts "[write] crontab file #{action}"
exit(0)
else
warn "[fail] Couldn't write crontab; try running `whenever' with no options to ensure your schedule file is valid."
exit(1)
end
warn "[fail] Couldn't write crontab; try running `whenever' with no options to ensure your schedule file is valid."
exit(1)
end
end
def updated_crontab
# Check for unopened or unclosed identifier blocks
if read_crontab =~ Regexp.new("^#{comment_open}\s*$") && (read_crontab =~ Regexp.new("^#{comment_close}\s*$")).nil?
if read_crontab =~ Regexp.new("^#{comment_open}$") && (read_crontab =~ Regexp.new("^#{comment_close}$")).nil?
warn "[fail] Unclosed indentifier; Your crontab file contains '#{comment_open}', but no '#{comment_close}'"
exit(1)
elsif (read_crontab =~ Regexp.new("^#{comment_open}\s*$")).nil? && read_crontab =~ Regexp.new("^#{comment_close}\s*$")
elsif (read_crontab =~ Regexp.new("^#{comment_open}$")).nil? && read_crontab =~ Regexp.new("^#{comment_close}$")
warn "[fail] Unopened indentifier; Your crontab file contains '#{comment_close}', but no '#{comment_open}'"
exit(1)
end
# If an existing identier block is found, replace it with the new cron entries
if read_crontab =~ Regexp.new("^#{comment_open}\s*$") && read_crontab =~ Regexp.new("^#{comment_close}\s*$")
if read_crontab =~ Regexp.new("^#{comment_open}$") && read_crontab =~ Regexp.new("^#{comment_close}$")
# If the existing crontab file contains backslashes they get lost going through gsub.
# .gsub('\\', '\\\\\\') preserves them. Go figure.
read_crontab.gsub(Regexp.new("^#{comment_open}\s*$.+^#{comment_close}\s*$", Regexp::MULTILINE), whenever_cron.chomp.gsub('\\', '\\\\\\'))
read_crontab.gsub(Regexp.new("^#{comment_open}$.+^#{comment_close}$", Regexp::MULTILINE), whenever_cron.chomp.gsub('\\', '\\\\\\'))
else # Otherwise, append the new cron entries after any existing ones
[read_crontab, whenever_cron].join("\n\n")
end.gsub(/\n{3,}/, "\n\n") # More than two newlines becomes just two.
end
end
def prepare(contents)
# Strip n lines from the top of the file as specified by the :cut option.
# Use split with a -1 limit option to ensure the join is able to rebuild
# the file with all of the original seperators in-tact.
stripped_contents = contents.split($/,-1)[@options[:cut]..-1].join($/)
# Some cron implementations require all non-comment lines to be newline-
# terminated. (issue #95) Strip all newlines and replace with the default
# platform record seperator ($/)
stripped_contents.gsub!(/\s+$/, $/)
contents.split("\n")[@options[:cut]..-1].join("\n")
end
def comment_base
@ -149,12 +121,5 @@ module Whenever
"# End #{comment_base}"
end
def stdin
$stdin
end
def stdout
$stdout
end
end
end

View File

@ -1,24 +1,19 @@
module Whenever
module Output
class Cron
REGEX = /^.+ .+ .+ .+ .+.?$/
attr_accessor :time, :task
def initialize(time = nil, task = nil, at = nil)
def initialize(time = nil, task = nil, at = nil, output_redirection = nil)
@time = time
@task = task
@at = at.is_a?(String) ? (Chronic.parse(at) || 0) : (at || 0)
@output_redirection = output_redirection
end
def self.enumerate(item, detect_cron = true)
def self.enumerate(item)
if item and item.is_a?(String)
items =
if detect_cron && item =~ REGEX
[item]
else
item.split(',')
end
items = item.split(',')
else
items = item
items = [items] unless items and items.respond_to?(:each)
@ -28,48 +23,42 @@ module Whenever
def self.output(times, job)
enumerate(times).each do |time|
enumerate(job.at, false).each do |at|
yield new(time, job.output, at).output
enumerate(job.at).each do |at|
yield new(time, job.output, at, job.output_redirection).output
end
end
end
def output
[time_in_cron_syntax, task].compact.join(' ').strip
[time_in_cron_syntax, task, output_redirection].compact.join(' ').strip
end
def time_in_cron_syntax
case @time
when REGEX then @time # raw cron sytax given
when Symbol then parse_symbol
when String then parse_as_string
else parse_time
end
end
def output_redirection
Whenever::Output::Cron::OutputRedirection.new(@output_redirection).to_s unless @output_redirection == :not_set
end
protected
def parse_symbol
shortcut = case @time
when :reboot then '@reboot'
when :year then 12.months
when :yearly,
:annually then '@annually'
when :day then 1.day
when :daily then '@daily'
when :midnight then '@midnight'
when :month then 1.month
when :monthly then '@monthly'
when :week then 1.week
when :weekly then '@weekly'
when :hour then 1.hour
when :hourly then '@hourly'
when :reboot then '@reboot'
when :year, :yearly then '@annually'
when :day, :daily then '@daily'
when :midnight then '@midnight'
when :month, :monthly then '@monthly'
when :week, :weekly then '@weekly'
when :hour, :hourly then '@hourly'
end
if shortcut.is_a?(Numeric)
@time = shortcut
parse_time
elsif shortcut
if shortcut
if @at.is_a?(Time) || (@at.is_a?(Numeric) && @at > 0)
raise ArgumentError, "You cannot specify an ':at' when using the shortcuts for times."
else
@ -142,6 +131,7 @@ module Whenever
output[0, max_occurances].join(',')
end
end
end
end

View File

@ -1,28 +1,21 @@
module Whenever
class Job
attr_reader :at
attr_reader :at, :output_redirection
def initialize(options = {})
@options = options
@at = options.delete(:at)
@template = options.delete(:template)
@job_template = options.delete(:job_template) || ":job"
@options[:output] = Whenever::Output::Redirection.new(options[:output]).to_s if options.has_key?(:output)
@at = options[:at]
@output_redirection = options.has_key?(:output) ? options[:output] : :not_set
@options[:environment] ||= :production
@options[:path] ||= Whenever.path
end
def output
job = process_template(@template, @options).strip
process_template(@job_template, { :job => job }).strip
end
protected
def process_template(template, options)
template.gsub(/:\w+/) do |key|
@options[:template].dup.gsub(/:\w+/) do |key|
before_and_after = [$`[-1..-1], $'[0..0]]
option = options[key.sub(':', '').to_sym]
option = @options[key.sub(':', '').to_sym]
if before_and_after.all? { |c| c == "'" }
escape_single_quotes(option)
@ -33,6 +26,8 @@ module Whenever
end
end
end
protected
def escape_single_quotes(str)
str.gsub(/'/) { "'\\''" }
@ -41,5 +36,6 @@ module Whenever
def escape_double_quotes(str)
str.gsub(/"/) { '\"' }
end
end
end

View File

@ -1,27 +1,31 @@
module Whenever
class JobList
def initialize(options)
@jobs, @env, @set_variables, @pre_set_variables = {}, {}, {}, {}
@jobs, @env, @set_variables = {}, {}, {}
if options.is_a? String
options = { :string => options }
end
pre_set(options[:set])
setup = File.read("#{File.expand_path(File.dirname(__FILE__))}/setup.rb")
schedule = if options[:string]
options[:string]
elsif options[:file]
File.read(options[:file])
case options
when String
config = options
when Hash
config = if options[:string]
options[:string]
elsif options[:file]
File.read(options[:file])
end
pre_set(options[:set])
end
instance_eval(setup + schedule, options[:file] || '<eval>')
# Load all job type files.
Dir["#{File.expand_path(File.dirname(__FILE__))}/job_types/*.rb"].each do |file|
eval(File.read(file))
end
eval(config)
end
def set(variable, value)
variable = variable.to_sym
return if @pre_set_variables[variable]
return if instance_variable_defined?("@#{variable}".to_sym)
instance_variable_set("@#{variable}".to_sym, value)
self.class.send(:attr_reader, variable.to_sym)
@ -55,7 +59,9 @@ module Whenever
end
end
def generate_cron_output
def generate_cron_output
set_path_environment_variable
[environment_variables, cron_jobs].compact.join
end
@ -73,20 +79,29 @@ module Whenever
pairs.each do |pair|
next unless pair.index('=')
variable, value = *pair.split('=')
unless variable.blank? || value.blank?
variable = variable.strip.to_sym
set(variable, value.strip)
@pre_set_variables[variable] = value
end
set(variable.strip.to_sym, value.strip) unless variable.blank? || value.blank?
end
end
def set_path_environment_variable
return if path_should_not_be_set_automatically?
@env[:PATH] = read_path unless read_path.blank?
end
def read_path
ENV['PATH'] if ENV
end
def path_should_not_be_set_automatically?
@set_path_automatically === false || @env[:PATH] || @env["PATH"]
end
def environment_variables
return if @env.empty?
output = []
@env.each do |key, val|
output << "#{key}=#{val.blank? ? '""' : val}\n"
output << "#{key}=#{val}\n"
end
output << "\n"
@ -141,5 +156,6 @@ module Whenever
shortcut_jobs.join + combine(regular_jobs).join
end
end
end

View File

@ -0,0 +1,8 @@
job_type :command, ":task"
job_type :rake, "cd :path && RAILS_ENV=:environment rake :task --silent"
if File.exists?(File.join(Whenever.path, 'script', 'rails'))
job_type :runner, "cd :path && script/rails runner -e :environment ':task'"
else
job_type :runner, "cd :path && script/runner -e :environment ':task'"
end

View File

@ -1,55 +1,59 @@
module Whenever
module Output
class Redirection
def initialize(output)
@output = output
end
def to_s
return '' unless defined?(@output)
case @output
when String then redirect_from_string
when Hash then redirect_from_hash
when NilClass then ">> /dev/null 2>&1"
else ''
end
end
protected
def stdout
return unless @output.has_key?(:standard)
@output[:standard].nil? ? '/dev/null' : @output[:standard]
end
def stderr
return unless @output.has_key?(:error)
@output[:error].nil? ? '/dev/null' : @output[:error]
end
def redirect_from_hash
case
when stdout == '/dev/null' && stderr == '/dev/null'
"> /dev/null 2>&1"
when stdout && stderr == '/dev/null'
">> #{stdout} 2> /dev/null"
when stdout && stderr
">> #{stdout} 2>> #{stderr}"
when stderr == '/dev/null'
"2> /dev/null"
when stderr
"2>> #{stderr}"
when stdout == '/dev/null'
"> /dev/null"
when stdout
">> #{stdout}"
else
''
class Cron
class OutputRedirection
def initialize(output)
@output = output
end
def to_s
return '' unless defined?(@output)
case @output
when String then redirect_from_string
when Hash then redirect_from_hash
when NilClass then ">> /dev/null 2>&1"
else ''
end
end
protected
def stdout
return unless @output.has_key?(:standard)
@output[:standard].nil? ? '/dev/null' : @output[:standard]
end
end
def redirect_from_string
">> #{@output} 2>&1"
def stderr
return unless @output.has_key?(:error)
@output[:error].nil? ? '/dev/null' : @output[:error]
end
def redirect_from_hash
case
when stdout == '/dev/null' && stderr == '/dev/null'
"> /dev/null 2>&1"
when stdout && stderr == '/dev/null'
">> #{stdout} 2> /dev/null"
when stdout && stderr
">> #{stdout} 2>> #{stderr}"
when stderr == '/dev/null'
"2> /dev/null"
when stderr
"2>> #{stderr}"
when stdout == '/dev/null'
"> /dev/null"
when stdout
">> #{stdout}"
else
''
end
end
def redirect_from_string
">> #{@output} 2>&1"
end
end
end
end

View File

@ -1,24 +0,0 @@
# Environemnt defaults to production
set :environment, "production"
# Path defaults to the directory `whenever` was run from
set :path, Whenever.path
# All jobs are wrapped in this template.
# http://blog.scoutapp.com/articles/2010/09/07/rvm-and-cron-in-production
set :job_template, "/bin/bash -l -c ':job'"
job_type :command, ":task :output"
# Run rake through bundler if possible
if Whenever.bundler?
job_type :rake, "cd :path && RAILS_ENV=:environment bundle exec rake :task --silent :output"
else
job_type :rake, "cd :path && RAILS_ENV=:environment rake :task --silent :output"
end
# Create a runner job that's appropriate for the Rails version,
if Whenever.rails3?
job_type :runner, "cd :path && script/rails runner -e :environment ':task' :output"
else
job_type :runner, "cd :path && script/runner -e :environment ':task' :output"
end

View File

@ -1,3 +1,3 @@
module Whenever
VERSION = '0.6.8'
end
VERSION = '0.5.3'
end unless defined?(Whenever::VERSION)

View File

@ -120,18 +120,35 @@ NEW_CRON
end
should "append the similarly named command" do
assert_equal @existing + "\n" + @new, @command.send(:updated_crontab)
assert_equal @existing + "\n\n" + @new, @command.send(:updated_crontab)
end
end
context "A command line clear" do
context "A command line delete" do
setup do
File.expects(:exists?).with('config/schedule.rb').returns(true)
@command = Whenever::CommandLine.new(:clear => true, :identifier => 'My identifier')
@task = "#{two_hours} /my/command"
end
should "clear an existing block if the identifier matches" do
should "add an empty identifier block if there is no existing one" do
existing = '# Existing crontab'
@command.expects(:read_crontab).at_least_once.returns(existing)
new_cron = <<-EXPECTED
#{existing}
# Begin Whenever generated tasks for: My identifier
# End Whenever generated tasks for: My identifier
EXPECTED
assert_equal new_cron, @command.send(:updated_crontab)
@command.expects(:write_crontab).with(new_cron).returns(true)
assert @command.run
end
should "delete an existing block if the identifier matches" do
existing = <<-EXISTING_CRON
# Something
@ -145,17 +162,20 @@ This shouldn't get replaced
EXISTING_CRON
@command.expects(:read_crontab).at_least_once.returns(existing)
new_cron = <<-NEW_CRON
# Something
# Begin Whenever generated tasks for: My identifier
# End Whenever generated tasks for: My identifier
# Begin Whenever generated tasks for: Other identifier
This shouldn't get replaced
# End Whenever generated tasks for: Other identifier
NEW_CRON
assert_equal new_cron, @command.send(:updated_crontab)
@command.expects(:write_crontab).with(new_cron).returns(true)
assert @command.run
end
@ -197,7 +217,6 @@ NEW_CRON
setup do
@output = Whenever.cron :set => 'environment=serious', :string => \
<<-file
set :job_template, nil
set :environment, :silly
set :path, '/my/path'
every 2.hours do
@ -215,7 +234,6 @@ NEW_CRON
setup do
@output = Whenever.cron :set => 'environment=serious&path=/serious/path', :string => \
<<-file
set :job_template, nil
set :environment, :silly
set :path, '/silly/path'
every 2.hours do
@ -233,7 +251,6 @@ NEW_CRON
setup do
@output = Whenever.cron :set => ' environment = serious& path =/serious/path', :string => \
<<-file
set :job_template, nil
set :environment, :silly
set :path, '/silly/path'
every 2.hours do
@ -251,7 +268,6 @@ NEW_CRON
setup do
@output = Whenever.cron :set => ' environment=', :string => \
<<-file
set :job_template, nil
set :environment, :silly
set :path, '/silly/path'
every 2.hours do
@ -281,7 +297,8 @@ My whenever job that was already here
# End Whenever generated tasks for: My identifier
EXISTING_CRON
assert_equal existing, @command.send(:prepare, existing)
# here-doc adds an extra newline we need removed
assert_equal existing.strip, @command.send(:prepare, existing)
end
should "trim off the top lines of the file" do
@ -301,61 +318,8 @@ My whenever job that was already here
# End Whenever generated tasks for: My identifier
NEW_CRON
assert_equal new_cron, @command.send(:prepare, existing)
end
should "preserve terminating newlines in files" do
@command = Whenever::CommandLine.new(:update => true, :identifier => 'My identifier')
existing = <<-EXISTING_CRON
# Begin Whenever generated tasks for: My identifier
My whenever job that was already here
# End Whenever generated tasks for: My identifier
# A non-Whenever task
My non-whenever job that was already here
EXISTING_CRON
assert_equal existing, @command.send(:prepare, existing)
end
end
context 'A command line update that reads the cron from stdin writes to stdout' do
setup do
@mock_stdin = StringIO.new(<<-EXISTING_CRON)
# Something
# Begin Whenever generated tasks for: My identifier
My whenever job that was already here
# End Whenever generated tasks for: My identifier
EXISTING_CRON
@mock_stdout = StringIO.new
@mock_stdin.stubs(:tty?).returns(false)
File.expects(:exists?).with('config/schedule.rb').returns(true)
@command = Whenever::CommandLine.new(:update => true, :identifier => 'My identifier')
@task = "#{two_hours} /my/command"
Whenever.expects(:cron).returns(@task)
@command.stubs(:stdin).returns(@mock_stdin)
@command.stubs(:stdout).returns(@mock_stdout)
end
should "update the file and write out a new file correctly" do
begin
@command.run
@mock_stdout.rewind
asset_equal @mock_stdout.read, <<-NEW_CRON
# Something
# Begin Whenever generated tasks for: My identifier
#{@task}
# End Whenever generated tasks for: My identifier
NEW_CRON
rescue SystemExit => e
assert_equal 0, e.status
end
# here-doc adds an extra newline we need removed
assert_equal new_cron.strip, @command.send(:prepare, existing)
end
end

View File

@ -6,7 +6,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every "weekday", :at => '5:02am' do
command "blahblah"
end
@ -22,7 +21,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every "weekday", :at => %w(5:02am 3:52pm) do
command "blahblah"
end
@ -39,7 +37,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every "weekday", :at => '5:02am, 3:52pm' do
command "blahblah"
end
@ -56,7 +53,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every "weekday", :at => '5:02am, 3:02pm' do
command "blahblah"
end
@ -72,7 +68,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every "mon,wed,fri", :at => '5:02am, 3:02pm' do
command "blahblah"
end
@ -88,7 +83,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/your/path'
every "mon,wed,fri", :at => '5:02am, 3:02pm' do
runner "blahblah"
@ -105,7 +99,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/your/path'
every "mon,wed,fri", :at => '5:02am, 3:02pm' do
rake "blah:blah"
@ -114,7 +107,7 @@ class OutputAtTest < Test::Unit::TestCase
end
should "output the rake task using one entry because the times are aligned" do
assert_match '2 5,15 * * 1,3,5 cd /your/path && RAILS_ENV=production bundle exec rake blah:blah --silent', @output
assert_match '2 5,15 * * 1,3,5 cd /your/path && RAILS_ENV=production rake blah:blah --silent', @output
end
end
@ -122,7 +115,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every [1.month, 1.day], :at => 'january 5:02am, june 17th at 2:22pm, june 3rd at 3:33am' do
command "blahblah"
end
@ -146,7 +138,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every :reboot do
command "command_1"
command "command_2"
@ -164,9 +155,8 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/your/path'
every :daily do
every :day do
rake "blah:blah"
runner "runner_1"
command "command_1"
@ -177,7 +167,7 @@ class OutputAtTest < Test::Unit::TestCase
end
should "output all of the commands @daily" do
assert_match '@daily cd /your/path && RAILS_ENV=production bundle exec rake blah:blah --silent', @output
assert_match '@daily cd /your/path && RAILS_ENV=production rake blah:blah --silent', @output
assert_match %(@daily cd /your/path && script/runner -e production 'runner_1'), @output
assert_match '@daily command_1', @output
assert_match %(@daily cd /your/path && script/runner -e production 'runner_2'), @output
@ -189,7 +179,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 5.minutes, :at => 1 do
command "blahblah"
end
@ -205,7 +194,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 4.minutes, :at => 2 do
command "blahblah"
end
@ -221,7 +209,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 3.minutes, :at => 7 do
command "blahblah"
end
@ -237,7 +224,6 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.minutes, :at => 27 do
command "blahblah"
end
@ -248,21 +234,4 @@ class OutputAtTest < Test::Unit::TestCase
assert_match '27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59 * * * * blahblah', @output
end
end
context "using raw cron syntax" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every '0 0 27,31 * *' do
command "blahblah"
end
file
end
should "output the command using the same cron syntax" do
assert_match '0 0 27,31 * * blahblah', @output
end
end
end

View File

@ -4,11 +4,10 @@ class OutputDefaultDefinedJobsTest < Test::Unit::TestCase
# command
context "A plain command with the job template set to nil" do
context "A plain command" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah"
end
@ -20,64 +19,12 @@ class OutputDefaultDefinedJobsTest < Test::Unit::TestCase
end
end
context "A plain command with no job template set" do
setup do
@output = Whenever.cron \
<<-file
every 2.hours do
command "blahblah"
end
file
end
should "output the command with the default job template" do
assert_match /^.+ .+ .+ .+ \/bin\/bash -l -c 'blahblah'$/, @output
end
end
context "A plain command that overrides the job_template set" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, "/bin/bash -l -c ':job'"
every 2.hours do
command "blahblah", :job_template => "/bin/sh -l -c ':job'"
end
file
end
should "output the command using that job_template" do
assert_match /^.+ .+ .+ .+ \/bin\/sh -l -c 'blahblah'$/, @output
assert_no_match /bash/, @output
end
end
context "A plain command that is conditional on default environent and path" do
setup do
Whenever.expects(:path).at_least_once.returns('/what/you/want')
@output = Whenever.cron \
<<-file
set :job_template, nil
if environment == 'production' && path == '/what/you/want'
every 2.hours do
command "blahblah"
end
end
file
end
should "output the command" do
assert_match /blahblah/, @output
end
end
# runner
context "A runner with path set" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/my/path'
every 2.hours do
runner 'blahblah'
@ -94,7 +41,6 @@ class OutputDefaultDefinedJobsTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/my/path'
every 2.hours do
runner "blahblah", :path => '/some/other/path'
@ -110,10 +56,9 @@ class OutputDefaultDefinedJobsTest < Test::Unit::TestCase
context "A runner for a Rails 3 app" do
setup do
Whenever.expects(:path).at_least_once.returns('/my/path')
Whenever.expects(:rails3?).returns(true)
File.expects(:exists?).with('/my/path/script/rails').returns(true)
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
runner 'blahblah'
end
@ -131,7 +76,6 @@ class OutputDefaultDefinedJobsTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/my/path'
every 2.hours do
rake "blahblah"
@ -140,24 +84,6 @@ class OutputDefaultDefinedJobsTest < Test::Unit::TestCase
end
should "output the rake command using that path" do
assert_match two_hours + ' cd /my/path && RAILS_ENV=production bundle exec rake blahblah --silent', @output
end
end
context "A rake for a non-bundler app" do
setup do
Whenever.expects(:path).at_least_once.returns('/my/path')
Whenever.expects(:bundler?).returns(false)
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
rake 'blahblah'
end
file
end
should "not use invoke through bundler" do
assert_match two_hours + ' cd /my/path && RAILS_ENV=production rake blahblah --silent', @output
end
end
@ -166,7 +92,6 @@ class OutputDefaultDefinedJobsTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/my/path'
every 2.hours do
rake "blahblah", :path => '/some/other/path'
@ -175,7 +100,7 @@ class OutputDefaultDefinedJobsTest < Test::Unit::TestCase
end
should "output the rake command using that path" do
assert_match two_hours + ' cd /some/other/path && RAILS_ENV=production bundle exec rake blahblah --silent', @output
assert_match two_hours + ' cd /some/other/path && RAILS_ENV=production rake blahblah --silent', @output
end
end

View File

@ -6,7 +6,6 @@ class OutputDefinedJobTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
job_type :some_job, "before :task after"
every 2.hours do
some_job "during"
@ -23,7 +22,6 @@ class OutputDefinedJobTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
job_type :some_job, "before :task after :option1 :option2"
every 2.hours do
some_job "during", :option1 => 'happy', :option2 => 'birthday'
@ -40,7 +38,6 @@ class OutputDefinedJobTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
job_type :some_job, "before :task after :option1"
set :option1, 'happy'
every 2.hours do
@ -58,7 +55,6 @@ class OutputDefinedJobTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
job_type :some_job, "before :task after :option1"
set :option1, 'global'
every 2.hours do
@ -76,7 +72,6 @@ class OutputDefinedJobTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
job_type :some_job, "before :task after :option1"
every 2.hours do
some_job "during", :option2 => 'happy'
@ -95,7 +90,6 @@ class OutputDefinedJobTest < Test::Unit::TestCase
@output = Whenever.cron \
<<-file
set :job_template, nil
job_type :some_job, "cd :path && :task"
every 2.hours do
some_job 'blahblah'

View File

@ -8,8 +8,6 @@ class OutputEnvTest < Test::Unit::TestCase
<<-file
env :MYVAR, 'blah'
env 'MAILTO', "someone@example.com"
env :BLANKVAR, ''
env :NILVAR, nil
file
end
@ -20,14 +18,39 @@ class OutputEnvTest < Test::Unit::TestCase
should "output MAILTO environment variable" do
assert_match "MAILTO=someone@example.com", @output
end
should "output BLANKVAR environment variable" do
assert_match "BLANKVAR=\"\"", @output
end
context "No PATH environment variable set" do
setup do
Whenever::JobList.any_instance.expects(:read_path).at_least_once.returns('/usr/local/bin')
@output = Whenever.cron ""
end
should "output NILVAR environment variable" do
assert_match "NILVAR=\"\"", @output
should "add a PATH variable based on the user's PATH" do
assert_match "PATH=/usr/local/bin", @output
end
end
context "A PATH environment variable set" do
setup do
Whenever::JobList.stubs(:read_path).returns('/usr/local/bin')
@output = Whenever.cron "env :PATH, '/my/path'"
end
should "use that path and the user's PATH" do
assert_match "PATH=/my/path", @output
assert_no_match /local/, @output
end
end
context "No PATH set and instructed not to automatically load the user's path" do
setup do
@output = Whenever.cron "set :set_path_automatically, false"
end
should "not have a PATH set" do
assert_no_match /PATH/, @output
end
end
end
end

View File

@ -6,7 +6,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :output, nil
every 2.hours do
command "blahblah"
@ -24,7 +23,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :output, 'logfile.log'
every 2.hours do
command "blahblah"
@ -41,7 +39,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:standard => 'dev_null', :error => 'dev_err'}
end
@ -57,7 +54,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :output, 'logfile.log'
every 2.hours do
command "blahblah", :output => 'otherlog.log'
@ -75,7 +71,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :output, 'logfile.log'
every 2.hours do
command "blahblah", :output => {:error => 'dev_err', :standard => 'dev_null' }
@ -93,7 +88,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :output, 'logfile.log'
every 2.hours do
command "blahblah", :output => false
@ -111,7 +105,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do
@output = Whenever.cron :set => 'output=otherlog.log', :string => \
<<-file
set :job_template, nil
set :output, 'logfile.log'
every 2.hours do
command "blahblah"
@ -129,7 +122,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :output, {:error => 'dev_err', :standard => 'dev_null' }
every 2.hours do
command "blahblah"
@ -146,7 +138,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :output, {:error => 'dev_null'}
every 2.hours do
command "blahblah"
@ -163,7 +154,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :output, {:standard => 'dev_out'}
every 2.hours do
command "blahblah"
@ -180,7 +170,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:error => 'dev_err'}
end
@ -196,7 +185,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:standard => 'dev_out'}
end
@ -212,7 +200,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:standard => nil}
end
@ -228,7 +215,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:error => nil}
end
@ -244,7 +230,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:error => nil, :standard => nil}
end
@ -260,7 +245,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:error => nil, :standard => 'my.log'}
end
@ -276,7 +260,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:error => 'my_error.log', :standard => nil}
end
@ -292,7 +275,6 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :cron_log, "cron.log"
every 2.hours do
command "blahblah"

View File

@ -174,26 +174,20 @@ class CronTest < Test::Unit::TestCase
context "When parsing time using the cron shortcuts" do
should "parse a :symbol into the correct shortcut" do
assert_equal '@reboot', parse_time(:reboot)
assert_equal '@annually', parse_time(:annually)
assert_equal '@annually', parse_time(:year)
assert_equal '@annually', parse_time(:yearly)
assert_equal '@daily', parse_time(:day)
assert_equal '@daily', parse_time(:daily)
assert_equal '@midnight', parse_time(:midnight)
assert_equal '@monthly', parse_time(:month)
assert_equal '@monthly', parse_time(:monthly)
assert_equal '@weekly', parse_time(:weekly)
assert_equal '@hourly', parse_time(:hour)
assert_equal '@hourly', parse_time(:hourly)
end
should "convert time-based shortcuts to times" do
assert_equal '0 0 1 * *', parse_time(:month)
assert_equal '0 0 * * *', parse_time(:day)
assert_equal '0 * * * *', parse_time(:hour)
assert_equal '0 0 1 12 *', parse_time(:year)
assert_equal '0 0 1,8,15,22 * *', parse_time(:week)
end
should "raise an exception if a valid shortcut is given but also an :at" do
assert_raises ArgumentError do
parse_time(:hourly, nil, "1:00 am")
parse_time(:hour, nil, "1:00 am")
end
assert_raises ArgumentError do
@ -201,16 +195,7 @@ class CronTest < Test::Unit::TestCase
end
assert_raises ArgumentError do
parse_time(:daily, nil, '4:20pm')
end
end
end
context "When given raw cron sytax" do
should "return the same cron sytax" do
crons = ['0 0 27-31 * *', '* * * * *', '2/3 1,9,22 11-26 1-6 *']
crons.each do |cron|
assert_equal cron, parse_time(cron)
parse_time(:day, nil, '4:20pm')
end
end
end

View File

@ -7,6 +7,14 @@ class JobTest < Test::Unit::TestCase
assert_equal 'foo', new_job(:at => 'foo').at
end
should "return :output when #output_redirection is called" do
assert_equal 'foo', new_job(:output => 'foo').output_redirection
end
should "return :not_set when #output_redirection is called and no :output is set" do
assert_equal :not_set, new_job.output_redirection
end
should "substitute the :task when #output is called" do
job = new_job(:template => ":task", :task => 'abc123')
assert_equal 'abc123', job.output
@ -24,6 +32,7 @@ class JobTest < Test::Unit::TestCase
context "A Job with quotes" do
should "output the :task if it's in single quotes" do
job = new_job(:template => "':task'", :task => 'abc123')
assert_equal %q('abc123'), job.output
@ -50,23 +59,6 @@ class JobTest < Test::Unit::TestCase
assert_equal %q(before "quote -> \" <- quote" after), job.output
end
end
context "A Job with a job_template" do
should "use the job template" do
job = new_job(:template => ':task', :task => 'abc123', :job_template => 'left :job right')
assert_equal 'left abc123 right', job.output
end
should "escape single quotes" do
job = new_job(:template => "before ':task' after", :task => "quote -> ' <- quote", :job_template => "left ':job' right")
assert_equal %q(left 'before '\''quote -> '\\''\\'\\'''\\'' <- quote'\'' after' right), job.output
end
should "escape double quotes" do
job = new_job(:template => 'before ":task" after', :task => 'quote -> " <- quote', :job_template => 'left ":job" right')
assert_equal %q(left "before \"quote -> \\\" <- quote\" after" right), job.output
end
end
private

View File

@ -1,31 +1,85 @@
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "whenever/version"
Gem::Specification.new do |s|
s.name = "whenever"
s.version = Whenever::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Javan Makhmali"]
s.email = ["javan@javan.us"]
s.homepage = ""
s.summary = %q{Cron jobs in ruby.}
s.description = %q{Clean ruby syntax for writing and deploying cron jobs.}
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- test/{functional,unit}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.name = %q{whenever}
s.version = "0.5.3"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Javan Makhmali"]
s.date = %q{2010-09-24}
s.description = %q{Clean ruby syntax for defining and deploying messy cron jobs.}
s.email = %q{javan@javan.us}
s.executables = ["whenever", "wheneverize"]
s.extra_rdoc_files = [
"README.rdoc"
]
s.files = [
".gitignore",
"CHANGELOG.rdoc",
"README.rdoc",
"Rakefile",
"bin/whenever",
"bin/wheneverize",
"lib/whenever.rb",
"lib/whenever/base.rb",
"lib/whenever/command_line.rb",
"lib/whenever/cron.rb",
"lib/whenever/job.rb",
"lib/whenever/job_list.rb",
"lib/whenever/job_types/default.rb",
"lib/whenever/output_redirection.rb",
"lib/whenever/version.rb",
"test/functional/command_line_test.rb",
"test/functional/output_at_test.rb",
"test/functional/output_default_defined_jobs_test.rb",
"test/functional/output_defined_job_test.rb",
"test/functional/output_env_test.rb",
"test/functional/output_redirection_test.rb",
"test/test_helper.rb",
"test/unit/cron_test.rb",
"test/unit/job_test.rb",
"whenever.gemspec"
]
s.homepage = %q{http://github.com/javan/whenever}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.add_dependency "chronic", ">= 0.4.3"
s.add_dependency "activesupport", ">= 2.3.4"
s.add_development_dependency "shoulda", ">= 2.1.1"
s.add_development_dependency "mocha", ">= 0.9.5"
s.add_development_dependency "rake"
# I'm not sure why this isn't installed along with activesupport,
# but for whatever reason running `bundle install` doesn't install
# i18n so I'm adding it here for now.
# https://github.com/rails/rails/blob/master/activesupport/activesupport.gemspec#L19 ?
s.add_development_dependency "i18n"
s.rubygems_version = %q{1.3.7}
s.summary = %q{Clean ruby syntax for defining and deploying messy cron jobs.}
s.test_files = [
"test/functional/command_line_test.rb",
"test/functional/output_at_test.rb",
"test/functional/output_default_defined_jobs_test.rb",
"test/functional/output_defined_job_test.rb",
"test/functional/output_env_test.rb",
"test/functional/output_redirection_test.rb",
"test/test_helper.rb",
"test/unit/cron_test.rb",
"test/unit/job_test.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<aaronh-chronic>, [">= 0.3.9"])
s.add_runtime_dependency(%q<activesupport>, [">= 2.3.4"])
s.add_development_dependency(%q<shoulda>, [">= 2.1.1"])
s.add_development_dependency(%q<mocha>, [">= 0.9.5"])
else
s.add_dependency(%q<aaronh-chronic>, [">= 0.3.9"])
s.add_dependency(%q<activesupport>, [">= 2.3.4"])
s.add_dependency(%q<shoulda>, [">= 2.1.1"])
s.add_dependency(%q<mocha>, [">= 0.9.5"])
end
else
s.add_dependency(%q<aaronh-chronic>, [">= 0.3.9"])
s.add_dependency(%q<activesupport>, [">= 2.3.4"])
s.add_dependency(%q<shoulda>, [">= 2.1.1"])
s.add_dependency(%q<mocha>, [">= 0.9.5"])
end
end