Compare commits

...

No commits in common. "master" and "gh-pages" have entirely different histories.

29 changed files with 78 additions and 2798 deletions

5
.gitignore vendored
View File

@ -1,5 +0,0 @@
.DS_Store
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,175 +0,0 @@
### 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
* 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
* Quotes automatically escaped in jobs. [Jay Adkisson]
* Added --cut option to the command line to allow pruning of the crontab. [Peer Allan]
* Switched to aaronh-chronic which is ruby 1.9.2 compatible. [Aaron Hurley, Javan Makhmali]
* Lots of internal reorganizing; tests broken into unit and functional. [Javan Makhmali]
### 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)]
* Jobs < 1.hour can specify an :at. [gorenje]
* --clear option to remove crontab entries for a specific [identifier]. [mraidel (Michael Raidel)]
### 0.4.2 / April 26th, 2010
* runners now cd into the app's directory and then execute. [Michael Guterl]
* Fix STDERR output redirection to file to append instead of overwrite. [weplay]
* Move require of tempfile lib to file that actually uses it. [Finn Smith]
* bugfix: comparison Time with 0 failed. #32 [Dan Hixon]
### 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
* 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
* No longer tries (and fails) to combine @shortcut jobs. #20 [Javan Makhmali]
### 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
* 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
* 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
* 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
* Days of week jobs can now accept an :at directive (ex: every :monday, :at => '5pm'). [David Eisinger]
* Fixed command line test so it runs without a config/schedule.rb present. [Javan Makhmali]
* 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
* 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
* 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
* Added --load-file and --user opts to whenever binary. [Javan Makhmali]
### 0.1.3 / February 16th, 2009
* Added 'rake' helper for defining scheduled rake tasks. [Javan Makhmali]
* Renamed :cron_environment and :cron_path to :enviroment and :path for better (word) compatibility with rake tasks. [Javan Makhmali]
* Improved test load paths so tests can be run individually. [Javan Makhmali]
* Got rid of already initialized constant warning. [Javan Makhmali]
* Requiring specific gem versions: Chronic >=0.2.3 and activesupport >= 1.3.0 [Javan Makhmali]
### 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

View File

@ -1,11 +0,0 @@
require 'bundler'
Bundler::GemHelper.install_tasks
require 'rake/testtask'
Rake::TestTask.new(:test) do |test|
test.libs << 'lib' << 'test'
test.pattern = 'test/{functional,unit}/**/*_test.rb'
test.verbose = true
end
task :default => :test

View File

@ -1,39 +0,0 @@
#!/usr/bin/env ruby
require 'rubygems'
require 'optparse'
require 'whenever'
require 'whenever/version'
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: whenever [options]"
opts.on('-i', '--update-crontab [identifier]', 'Default: full path to schedule.rb file') do |identifier|
options[:update] = true
options[:identifier] = identifier if identifier
end
opts.on('-w', '--write-crontab [identifier]', 'Default: full path to schedule.rb file') do |identifier|
options[:write] = true
options[:identifier] = identifier if identifier
end
opts.on('-c', '--clear-crontab [identifier]') do |identifier|
options[:clear] = true
options[:identifier] = identifier if identifier
end
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|
options[:file] = file if file
end
opts.on('-u', '--user [user]', 'Default: current user') do |user|
options[:user] = user if user
end
opts.on('-k', '--cut [lines]', 'Cut lines from the top of the cronfile') do |lines|
options[:cut] = lines.to_i if lines
end
opts.on('-v', '--version') { puts "Whenever v#{Whenever::VERSION}"; exit(0) }
end.parse!
Whenever::CommandLine.execute(options)

View File

@ -1,68 +0,0 @@
#!/usr/bin/env ruby
# This file is based heavily on Capistrano's `capify` command
require 'optparse'
require 'fileutils'
OptionParser.new do |opts|
opts.banner = "Usage: #{File.basename($0)} [path]"
begin
opts.parse!(ARGV)
rescue OptionParser::ParseError => e
warn e.message
puts opts
exit 1
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
end
content = <<-FILE
# Use this file to easily define all of your cron jobs.
#
# It's helpful, but not entirely necessary to understand cron before proceeding.
# http://en.wikipedia.org/wiki/Cron
# Example:
#
# set :output, "/path/to/my/cron_log.log"
#
# every 2.hours do
# command "/usr/bin/some_great_command"
# runner "MyModel.some_method"
# rake "some:great:rake:task"
# end
#
# every 4.days do
# runner "AnotherModel.prune_old_records"
# end
# Learn more: http://github.com/javan/whenever
FILE
file = 'config/schedule.rb'
base = ARGV.empty? ? '.' : ARGV.shift
file = File.join(base, file)
if File.exists?(file)
warn "[skip] `#{file}' already exists"
elsif File.exists?(file.downcase)
warn "[skip] `#{file.downcase}' exists, which could conflict with `#{file}'"
elsif !File.exists?(File.dirname(file))
warn "[skip] directory `#{File.dirname(file)}' does not exist"
else
puts "[add] writing `#{file}'"
File.open(file, "w") { |f| f.write(content) }
end
puts "[done] wheneverized!"

78
index.html Normal file
View File

@ -0,0 +1,78 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>javan/whenever @ GitHub</title>
<style type="text/css">
body {
margin-top: 1.0em;
background-color: #211b6a;
font-family: "helvetica";
color: #ffffff;
}
#container {
margin: 0 auto;
width: 700px;
}
h1 { font-size: 3.8em; color: #dee495; margin-bottom: 3px; }
h1 .small { font-size: 0.4em; }
h1 a { text-decoration: none }
h2 { font-size: 1.5em; color: #dee495; }
h3 { text-align: center; color: #dee495; }
a { color: #dee495; }
.description { font-size: 1.2em; margin-bottom: 30px; margin-top: 30px; font-style: italic;}
.download { float: right; }
pre { background: #000; color: #fff; padding: 15px;}
hr { border: 0; width: 80%; border-bottom: 1px solid #aaa}
.footer { text-align:center; padding-top:30px; font-style: italic; }
</style>
</head>
<body>
<a href="http://github.com/javan/whenever"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" /></a>
<div id="container">
<div class="download">
<a href="http://github.com/javan/whenever/zipball/master">
<img border="0" width="90" src="http://github.com/images/modules/download/zip.png"></a>
<a href="http://github.com/javan/whenever/tarball/master">
<img border="0" width="90" src="http://github.com/images/modules/download/tar.png"></a>
</div>
<h1><a href="http://github.com/javan/whenever">Whenever</a>
<span class="small">by <a href="http://github.com/javan">javan</a></small></h1>
<div class="description">
Provides clean ruby syntax for defining messy cron jobs and running them Whenever.
</div>
<h2>Authors</h2>
<p>Javan Makhmali -- javan [at] javan (dot) us <br/> <br/> </p>
<h2>Download</h2>
<p>
You can download this project in either
<a href="http://github.com/javan/whenever/zipball/master">zip</a> or
<a href="http://github.com/javan/whenever/tarball/master">tar</a> formats.
</p>
<p>You can also clone the project with <a href="http://git-scm.com">Git</a>
by running:
<pre>$ git clone git://github.com/javan/whenever</pre>
</p>
<div class="footer">
get the source code on GitHub : <a href="http://github.com/javan/whenever">javan/whenever</a>
</div>
</div>
</body>
</html>

View File

@ -1,30 +0,0 @@
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

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

@ -1,160 +0,0 @@
require 'fileutils'
require 'tempfile'
module Whenever
class CommandLine
def self.execute(options={})
new(options).run
end
def initialize(options={})
@options = options
@options[:file] ||= 'config/schedule.rb'
@options[:cut] ||= 0
@options[:identifier] ||= default_identifier
unless File.exists?(@options[:file])
warn("[fail] Can't find file: #{@options[:file]}")
exit(1)
end
if [@options[:update], @options[:write], @options[:clear]].compact.length > 1
warn("[fail] Can only update, write or clear. Choose one.")
exit(1)
end
unless @options[:cut].to_s =~ /[0-9]*/
warn("[fail] Can't cut negative lines from the crontab #{options[:cut]}")
exit(1)
end
@options[:cut] = @options[:cut].to_i
end
def run
if @options[:update] || @options[:clear]
write_crontab(updated_crontab)
elsif @options[:write]
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
protected
def default_identifier
File.expand_path(@options[:file])
end
def whenever_cron
return '' if @options[:clear]
@whenever_cron ||= [comment_open, Whenever.cron(@options), 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)
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
if !stdin.tty?
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
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?
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*$")
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 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('\\', '\\\\\\'))
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
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+$/, $/)
end
def comment_base
"Whenever generated tasks for: #{@options[:identifier]}"
end
def comment_open
"# Begin #{comment_base}"
end
def comment_close
"# End #{comment_base}"
end
def stdin
$stdin
end
def stdout
$stdout
end
end
end

View File

@ -1,147 +0,0 @@
module Whenever
module Output
class Cron
REGEX = /^.+ .+ .+ .+ .+.?$/
attr_accessor :time, :task
def initialize(time = nil, task = nil, at = nil)
@time = time
@task = task
@at = at.is_a?(String) ? (Chronic.parse(at) || 0) : (at || 0)
end
def self.enumerate(item, detect_cron = true)
if item and item.is_a?(String)
items =
if detect_cron && item =~ REGEX
[item]
else
item.split(',')
end
else
items = item
items = [items] unless items and items.respond_to?(:each)
end
items
end
def self.output(times, job)
enumerate(times).each do |time|
enumerate(job.at, false).each do |at|
yield new(time, job.output, at).output
end
end
end
def output
[time_in_cron_syntax, task].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
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'
end
if shortcut.is_a?(Numeric)
@time = shortcut
parse_time
elsif 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
return shortcut
end
else
parse_as_string
end
end
def parse_time
timing = Array.new(5, '*')
case @time
when 0.seconds...1.minute
raise ArgumentError, "Time must be in minutes or higher"
when 1.minute...1.hour
minute_frequency = @time / 60
timing[0] = comma_separated_timing(minute_frequency, 59, @at || 0)
when 1.hour...1.day
hour_frequency = (@time / 60 / 60).round
timing[0] = @at.is_a?(Time) ? @at.min : @at
timing[1] = comma_separated_timing(hour_frequency, 23)
when 1.day...1.month
day_frequency = (@time / 24 / 60 / 60).round
timing[0] = @at.is_a?(Time) ? @at.min : 0
timing[1] = @at.is_a?(Time) ? @at.hour : @at
timing[2] = comma_separated_timing(day_frequency, 31, 1)
when 1.month..12.months
month_frequency = (@time / 30 / 24 / 60 / 60).round
timing[0] = @at.is_a?(Time) ? @at.min : 0
timing[1] = @at.is_a?(Time) ? @at.hour : 0
timing[2] = @at.is_a?(Time) ? @at.day : (@at.zero? ? 1 : @at)
timing[3] = comma_separated_timing(month_frequency, 12, 1)
else
return parse_as_string
end
timing.join(' ')
end
def parse_as_string
return unless @time
string = @time.to_s
timing = Array.new(4, '*')
timing[0] = @at.is_a?(Time) ? @at.min : 0
timing[1] = @at.is_a?(Time) ? @at.hour : 0
return (timing << '1-5') * " " if string.downcase.index('weekday')
return (timing << '6,0') * " " if string.downcase.index('weekend')
%w(sun mon tue wed thu fri sat).each_with_index do |day, i|
return (timing << i) * " " if string.downcase.index(day)
end
raise ArgumentError, "Couldn't parse: #{@time}"
end
def comma_separated_timing(frequency, max, start = 0)
return start if frequency.blank? || frequency.zero?
return '*' if frequency == 1
return frequency if frequency > (max * 0.5).ceil
original_start = start
start += frequency unless (max + 1).modulo(frequency).zero? || start > 0
output = (start..max).step(frequency).to_a
max_occurances = (max.to_f / (frequency.to_f)).round
max_occurances += 1 if original_start.zero?
output[0, max_occurances].join(',')
end
end
end
end

View File

@ -1,45 +0,0 @@
module Whenever
class Job
attr_reader :at
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)
@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|
before_and_after = [$`[-1..-1], $'[0..0]]
option = options[key.sub(':', '').to_sym]
if before_and_after.all? { |c| c == "'" }
escape_single_quotes(option)
elsif before_and_after.all? { |c| c == '"' }
escape_double_quotes(option)
else
option
end
end
end
def escape_single_quotes(str)
str.gsub(/'/) { "'\\''" }
end
def escape_double_quotes(str)
str.gsub(/"/) { '\"' }
end
end
end

View File

@ -1,145 +0,0 @@
module Whenever
class JobList
def initialize(options)
@jobs, @env, @set_variables, @pre_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])
end
instance_eval(setup + schedule, options[:file] || '<eval>')
end
def set(variable, value)
variable = variable.to_sym
return if @pre_set_variables[variable]
instance_variable_set("@#{variable}".to_sym, value)
self.class.send(:attr_reader, variable.to_sym)
@set_variables[variable] = value
end
def env(variable, value)
@env[variable.to_s] = value
end
def every(frequency, options = {})
@current_time_scope = frequency
@options = options
yield
end
def job_type(name, template)
class_eval do
define_method(name) do |task, *args|
options = { :task => task, :template => template }
options.merge!(args[0]) if args[0].is_a? Hash
# :cron_log was an old option for output redirection, it remains for backwards compatibility
options[:output] = (options[:cron_log] || @cron_log) if defined?(@cron_log) || options.has_key?(:cron_log)
# :output is the newer, more flexible option.
options[:output] = @output if defined?(@output) && !options.has_key?(:output)
@jobs[@current_time_scope] ||= []
@jobs[@current_time_scope] << Whenever::Job.new(@options.merge(@set_variables).merge(options))
end
end
end
def generate_cron_output
[environment_variables, cron_jobs].compact.join
end
private
#
# Takes a string like: "variable1=something&variable2=somethingelse"
# and breaks it into variable/value pairs. Used for setting variables at runtime from the command line.
# Only works for setting values as strings.
#
def pre_set(variable_string = nil)
return if variable_string.blank?
pairs = variable_string.split('&')
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
end
end
def environment_variables
return if @env.empty?
output = []
@env.each do |key, val|
output << "#{key}=#{val.blank? ? '""' : val}\n"
end
output << "\n"
output.join
end
#
# Takes the standard cron output that Whenever generates and finds
# similar entries that can be combined. For example: If a job should run
# at 3:02am and 4:02am, instead of creating two jobs this method combines
# them into one that runs on the 2nd minute at the 3rd and 4th hour.
#
def combine(entries)
entries.map! { |entry| entry.split(/ +/, 6) }
0.upto(4) do |f|
(entries.length-1).downto(1) do |i|
next if entries[i][f] == '*'
comparison = entries[i][0...f] + entries[i][f+1..-1]
(i-1).downto(0) do |j|
next if entries[j][f] == '*'
if comparison == entries[j][0...f] + entries[j][f+1..-1]
entries[j][f] += ',' + entries[i][f]
entries.delete_at(i)
break
end
end
end
end
entries.map { |entry| entry.join(' ') }
end
def cron_jobs
return if @jobs.empty?
shortcut_jobs = []
regular_jobs = []
@jobs.each do |time, jobs|
jobs.each do |job|
Whenever::Output::Cron.output(time, job) do |cron|
cron << "\n\n"
if cron.starts_with?("@")
shortcut_jobs << cron
else
regular_jobs << cron
end
end
end
end
shortcut_jobs.join + combine(regular_jobs).join
end
end
end

View File

@ -1,56 +0,0 @@
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
''
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 +0,0 @@
module Whenever
VERSION = '0.6.8'
end

View File

@ -1,362 +0,0 @@
require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
class CommandLineTest < Test::Unit::TestCase
context "A command line write" do
setup do
File.expects(:exists?).with('config/schedule.rb').returns(true)
@command = Whenever::CommandLine.new(:write => true, :identifier => 'My identifier')
@task = "#{two_hours} /my/command"
Whenever.expects(:cron).returns(@task)
end
should "output the cron job with identifier blocks" do
output = <<-EXPECTED
# Begin Whenever generated tasks for: My identifier
#{@task}
# End Whenever generated tasks for: My identifier
EXPECTED
assert_equal output, @command.send(:whenever_cron)
end
should "write the crontab when run" do
@command.expects(:write_crontab).returns(true)
assert @command.run
end
end
context "A command line update" do
setup do
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)
end
should "add the cron to the end of the file if there is no existing identifier block" do
existing = '# Existing crontab'
@command.expects(:read_crontab).at_least_once.returns(existing)
new_cron = <<-EXPECTED
#{existing}
# Begin Whenever generated tasks for: My identifier
#{@task}
# 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 "replace an existing block if the identifier matches" do
existing = <<-EXISTING_CRON
# Something
# Begin Whenever generated tasks for: My identifier
My whenever job that was already here
# 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
EXISTING_CRON
new_cron = <<-NEW_CRON
# Something
# Begin Whenever generated tasks for: My identifier
#{@task}
# 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
@command.expects(:read_crontab).at_least_once.returns(existing)
assert_equal new_cron, @command.send(:updated_crontab)
@command.expects(:write_crontab).with(new_cron).returns(true)
assert @command.run
end
end
context "A command line update that contains backslashes" do
setup do
@existing = <<-EXISTING_CRON
# Begin Whenever generated tasks for: My identifier
script/runner -e production 'puts '\\''hello'\\'''
# End Whenever generated tasks for: My identifier
EXISTING_CRON
File.expects(:exists?).with('config/schedule.rb').returns(true)
@command = Whenever::CommandLine.new(:update => true, :identifier => 'My identifier')
@command.expects(:read_crontab).at_least_once.returns(@existing)
@command.expects(:whenever_cron).returns(@existing)
end
should "replace the existing block with the backslashes in tact" do
assert_equal @existing, @command.send(:updated_crontab)
end
end
context "A command line update with an identifier similar to an existing one in the crontab already" do
setup do
@existing = <<-EXISTING_CRON
# Begin Whenever generated tasks for: WheneverExisting
# End Whenever generated tasks for: WheneverExisting
EXISTING_CRON
@new = <<-NEW_CRON
# Begin Whenever generated tasks for: Whenever
# End Whenever generated tasks for: Whenever
NEW_CRON
File.expects(:exists?).with('config/schedule.rb').returns(true)
@command = Whenever::CommandLine.new(:update => true, :identifier => 'Whenever')
@command.expects(:read_crontab).at_least_once.returns(@existing)
@command.expects(:whenever_cron).returns(@new)
end
should "append the similarly named command" do
assert_equal @existing + "\n" + @new, @command.send(:updated_crontab)
end
end
context "A command line clear" 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
existing = <<-EXISTING_CRON
# Something
# Begin Whenever generated tasks for: My identifier
My whenever job that was already here
# 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
EXISTING_CRON
@command.expects(:read_crontab).at_least_once.returns(existing)
new_cron = <<-NEW_CRON
# Something
# 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
end
context "A command line update with no identifier" do
setup do
File.expects(:exists?).with('config/schedule.rb').returns(true)
Whenever::CommandLine.any_instance.expects(:default_identifier).returns('DEFAULT')
@command = Whenever::CommandLine.new(:update => true, :file => @file)
end
should "use the default identifier" do
assert_equal "Whenever generated tasks for: DEFAULT", @command.send(:comment_base)
end
end
context "combined params" do
setup do
Whenever::CommandLine.any_instance.expects(:exit)
Whenever::CommandLine.any_instance.expects(:warn)
File.expects(:exists?).with('config/schedule.rb').returns(true)
end
should "exit with write and clear" do
@command = Whenever::CommandLine.new(:write => true, :clear => true)
end
should "exit with write and update" do
@command = Whenever::CommandLine.new(:write => true, :update => true)
end
should "exit with update and clear" do
@command = Whenever::CommandLine.new(:update => true, :clear => true)
end
end
context "A runner where the environment is overridden using the :set option" do
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
runner "blahblah"
end
file
end
should "output the runner using the override environment" do
assert_match two_hours + %( cd /my/path && script/runner -e serious 'blahblah'), @output
end
end
context "A runner where the environment and path are overridden using the :set option" do
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
runner "blahblah"
end
file
end
should "output the runner using the overridden path and environment" do
assert_match two_hours + %( cd /serious/path && script/runner -e serious 'blahblah'), @output
end
end
context "A runner where the environment and path are overridden using the :set option with spaces in the string" do
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
runner "blahblah"
end
file
end
should "output the runner using the overridden path and environment" do
assert_match two_hours + %( cd /serious/path && script/runner -e serious 'blahblah'), @output
end
end
context "A runner where the environment is overridden using the :set option but no value is given" do
setup do
@output = Whenever.cron :set => ' environment=', :string => \
<<-file
set :job_template, nil
set :environment, :silly
set :path, '/silly/path'
every 2.hours do
runner "blahblah"
end
file
end
should "output the runner using the original environmnet" do
assert_match two_hours + %( cd /silly/path && script/runner -e silly 'blahblah'), @output
end
end
context "prepare-ing the output" do
setup do
File.expects(:exists?).with('config/schedule.rb').returns(true)
end
should "not trim off the top lines of the file" do
@command = Whenever::CommandLine.new(:update => true, :identifier => 'My identifier', :cut => 0)
existing = <<-EXISTING_CRON
# Useless Comments
# at the top of the file
# Begin Whenever generated tasks for: My identifier
My whenever job that was already here
# End Whenever generated tasks for: My identifier
EXISTING_CRON
assert_equal existing, @command.send(:prepare, existing)
end
should "trim off the top lines of the file" do
@command = Whenever::CommandLine.new(:update => true, :identifier => 'My identifier', :cut => '3')
existing = <<-EXISTING_CRON
# Useless Comments
# at the top of the file
# Begin Whenever generated tasks for: My identifier
My whenever job that was already here
# End Whenever generated tasks for: My identifier
EXISTING_CRON
new_cron = <<-NEW_CRON
# Begin Whenever generated tasks for: My identifier
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
end
end
end

View File

@ -1,268 +0,0 @@
require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
class OutputAtTest < Test::Unit::TestCase
context "weekday at a (single) given time" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every "weekday", :at => '5:02am' do
command "blahblah"
end
file
end
should "output the command using that time" do
assert_match '2 5 * * 1-5 blahblah', @output
end
end
context "weekday at a multiple diverse times, via an array" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every "weekday", :at => %w(5:02am 3:52pm) do
command "blahblah"
end
file
end
should "output the commands for both times given" do
assert_match '2 5 * * 1-5 blahblah', @output
assert_match '52 15 * * 1-5 blahblah', @output
end
end
context "weekday at a multiple diverse times, comma separated" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every "weekday", :at => '5:02am, 3:52pm' do
command "blahblah"
end
file
end
should "output the commands for both times given" do
assert_match '2 5 * * 1-5 blahblah', @output
assert_match '52 15 * * 1-5 blahblah', @output
end
end
context "weekday at a multiple aligned times" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every "weekday", :at => '5:02am, 3:02pm' do
command "blahblah"
end
file
end
should "output the command using one entry because the times are aligned" do
assert_match '2 5,15 * * 1-5 blahblah', @output
end
end
context "various days at a various aligned times" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every "mon,wed,fri", :at => '5:02am, 3:02pm' do
command "blahblah"
end
file
end
should "output the command using one entry because the times are aligned" do
assert_match '2 5,15 * * 1,3,5 blahblah', @output
end
end
context "various days at a various aligned times using a runner" do
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"
end
file
end
should "output the runner using one entry because the times are aligned" do
assert_match %(2 5,15 * * 1,3,5 cd /your/path && script/runner -e production 'blahblah'), @output
end
end
context "various days at a various aligned times using a rake task" do
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"
end
file
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
end
end
context "A command every 1.month at very diverse times" do
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
file
end
should "output 6 commands since none align" do
# The 1.month commands
assert_match '2 5 1 * * blahblah', @output
assert_match '22 14 17 * * blahblah', @output
assert_match '33 3 3 * * blahblah', @output
# The 1.day commands
assert_match '2 5 * * * blahblah', @output
assert_match '22 14 * * * blahblah', @output
assert_match '33 3 * * * blahblah', @output
end
end
context "Multiple commands output every :reboot" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every :reboot do
command "command_1"
command "command_2"
end
file
end
should "output both commands @reboot" do
assert_match "@reboot command_1", @output
assert_match "@reboot command_2", @output
end
end
context "Many different job types output every :day" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/your/path'
every :daily do
rake "blah:blah"
runner "runner_1"
command "command_1"
runner "runner_2"
command "command_2"
end
file
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 && 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
assert_match '@daily command_2', @output
end
end
context "every 5 minutes but but starting at 1" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 5.minutes, :at => 1 do
command "blahblah"
end
file
end
should "output the command using that time" do
assert_match '1,6,11,16,21,26,31,36,41,46,51,56 * * * * blahblah', @output
end
end
context "every 4 minutes but starting at 2" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 4.minutes, :at => 2 do
command "blahblah"
end
file
end
should "output the command using that time" do
assert_match '2,6,10,14,18,22,26,30,34,38,42,46,50,54,58 * * * * blahblah', @output
end
end
context "every 3 minutes but starting at 7" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 3.minutes, :at => 7 do
command "blahblah"
end
file
end
should "output the command using that time" do
assert_match '7,10,13,16,19,22,25,28,31,34,37,40,43,46,49,52,55,58 * * * * blahblah', @output
end
end
context "every 2 minutes but starting at 27" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.minutes, :at => 27 do
command "blahblah"
end
file
end
should "output the command using that time" do
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

@ -1,182 +0,0 @@
require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
class OutputDefaultDefinedJobsTest < Test::Unit::TestCase
# command
context "A plain command with the job template set to nil" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah"
end
file
end
should "output the command" do
assert_match /^.+ .+ .+ .+ blahblah$/, @output
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'
end
file
end
should "output the runner using that path" do
assert_match two_hours + %( cd /my/path && script/runner -e production 'blahblah'), @output
end
end
context "A runner that overrides the path set" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/my/path'
every 2.hours do
runner "blahblah", :path => '/some/other/path'
end
file
end
should "output the runner using that path" do
assert_match two_hours + %( cd /some/other/path && script/runner -e production 'blahblah'), @output
end
end
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)
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
runner 'blahblah'
end
file
end
should "use the Rails 3 runner job by default" do
assert_match two_hours + %( cd /my/path && script/rails runner -e production 'blahblah'), @output
end
end
# rake
context "A rake command with path set" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/my/path'
every 2.hours do
rake "blahblah"
end
file
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
context "A rake command that overrides the path set" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/my/path'
every 2.hours do
rake "blahblah", :path => '/some/other/path'
end
file
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
end
end
end

View File

@ -1,111 +0,0 @@
require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
class OutputDefinedJobTest < Test::Unit::TestCase
context "A defined job with a :task" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
job_type :some_job, "before :task after"
every 2.hours do
some_job "during"
end
file
end
should "output the defined job with the task" do
assert_match /^.+ .+ .+ .+ before during after$/, @output
end
end
context "A defined job with a :task and some options" do
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'
end
file
end
should "output the defined job with the task and options" do
assert_match /^.+ .+ .+ .+ before during after happy birthday$/, @output
end
end
context "A defined job with a :task and an option where the option is set globally" do
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
some_job "during"
end
file
end
should "output the defined job with the task and options" do
assert_match /^.+ .+ .+ .+ before during after happy$/, @output
end
end
context "A defined job with a :task and an option where the option is set globally and locally" do
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
some_job "during", :option1 => 'local'
end
file
end
should "output the defined job using the local option" do
assert_match /^.+ .+ .+ .+ before during after local$/, @output
end
end
context "A defined job with a :task and an option that is not set" do
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'
end
file
end
should "output the defined job with that option removed" do
assert_match /^.+ .+ .+ .+ before during after$/, @output
end
end
context "A defined job that uses a :path where none is explicitly set" do
setup do
Whenever.stubs(:path).returns('/my/path')
@output = Whenever.cron \
<<-file
set :job_template, nil
job_type :some_job, "cd :path && :task"
every 2.hours do
some_job 'blahblah'
end
file
end
should "default to using the Whenever.path" do
assert_match two_hours + %( cd /my/path && blahblah), @output
end
end
end

View File

@ -1,33 +0,0 @@
require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
class OutputEnvTest < Test::Unit::TestCase
context "The output from Whenever with environment variables set" do
setup do
@output = Whenever.cron \
<<-file
env :MYVAR, 'blah'
env 'MAILTO', "someone@example.com"
env :BLANKVAR, ''
env :NILVAR, nil
file
end
should "output MYVAR environment variable" do
assert_match "MYVAR=blah", @output
end
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
should "output NILVAR environment variable" do
assert_match "NILVAR=\"\"", @output
end
end
end

View File

@ -1,307 +0,0 @@
require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
class OutputRedirectionTest < Test::Unit::TestCase
context "A command when the output is set to nil" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :output, nil
every 2.hours do
command "blahblah"
end
file
end
should "output the command with the log syntax appended" do
assert_match /^.+ .+ .+ .+ blahblah >> \/dev\/null 2>&1$/, @output
end
end
context "A command when the output is set" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :output, 'logfile.log'
every 2.hours do
command "blahblah"
end
file
end
should "output the command with the log syntax appended" do
assert_match /^.+ .+ .+ .+ blahblah >> logfile.log 2>&1$/, @output
end
end
context "A command when the error and standard output is set by the command" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:standard => 'dev_null', :error => 'dev_err'}
end
file
end
should "output the command without the log syntax appended" do
assert_match /^.+ .+ .+ .+ blahblah >> dev_null 2>> dev_err$/, @output
end
end
context "A command when the output is set and the comand overrides it" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :output, 'logfile.log'
every 2.hours do
command "blahblah", :output => 'otherlog.log'
end
file
end
should "output the command with the command syntax appended" do
assert_no_match /.+ .+ .+ .+ blahblah >> logfile.log 2>&1/, @output
assert_match /^.+ .+ .+ .+ blahblah >> otherlog.log 2>&1$/, @output
end
end
context "A command when the output is set and the comand overrides with standard and error" do
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' }
end
file
end
should "output the command with the overridden redirection syntax appended" do
assert_no_match /.+ .+ .+ .+ blahblah >> logfile.log 2>&1/, @output
assert_match /^.+ .+ .+ .+ blahblah >> dev_null 2>> dev_err$/, @output
end
end
context "A command when the output is set and the comand rejects it" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :output, 'logfile.log'
every 2.hours do
command "blahblah", :output => false
end
file
end
should "output the command without the log syntax appended" do
assert_no_match /.+ .+ .+ .+ blahblah >> logfile.log 2>&1/, @output
assert_match /^.+ .+ .+ .+ blahblah$/, @output
end
end
context "A command when the output is set and is overridden by the :set option" do
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"
end
file
end
should "output the otherlog.log as the log file" do
assert_no_match /.+ .+ .+ .+ blahblah >> logfile.log 2>&1/, @output
assert_match /^.+ .+ .+ .+ blahblah >> otherlog.log 2>&1/, @output
end
end
context "A command when the error and standard output is set" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :output, {:error => 'dev_err', :standard => 'dev_null' }
every 2.hours do
command "blahblah"
end
file
end
should "output the command without the redirection syntax appended" do
assert_match /^.+ .+ .+ .+ blahblah >> dev_null 2>> dev_err$/, @output
end
end
context "A command when error output is set" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :output, {:error => 'dev_null'}
every 2.hours do
command "blahblah"
end
file
end
should "output the command without the standard error syntax appended" do
assert_match /^.+ .+ .+ .+ blahblah 2>> dev_null$/, @output
end
end
context "A command when the standard output is set" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :output, {:standard => 'dev_out'}
every 2.hours do
command "blahblah"
end
file
end
should "output the command with standard output syntax appended" do
assert_match /^.+ .+ .+ .+ blahblah >> dev_out$/, @output
end
end
context "A command when error output is set by the command" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:error => 'dev_err'}
end
file
end
should "output the command without the log syntax appended" do
assert_match /^.+ .+ .+ .+ blahblah 2>> dev_err$/, @output
end
end
context "A command when standard output is set by the command" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:standard => 'dev_out'}
end
file
end
should "output the command without the log syntax appended" do
assert_match /^.+ .+ .+ .+ blahblah >> dev_out$/, @output
end
end
context "A command when standard output is set to nil" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:standard => nil}
end
file
end
should "output the command with stdout directed to /dev/null" do
assert_match /^.+ .+ .+ .+ blahblah > \/dev\/null$/, @output
end
end
context "A command when standard error is set to nil" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:error => nil}
end
file
end
should "output the command with stderr directed to /dev/null" do
assert_match /^.+ .+ .+ .+ blahblah 2> \/dev\/null$/, @output
end
end
context "A command when standard output and standard error is set to nil" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:error => nil, :standard => nil}
end
file
end
should "output the command with stderr directed to /dev/null" do
assert_match /^.+ .+ .+ .+ blahblah > \/dev\/null 2>&1$/, @output
end
end
context "A command when standard output is set and standard error is set to nil" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:error => nil, :standard => 'my.log'}
end
file
end
should "output the command with stderr directed to /dev/null" do
assert_match /^.+ .+ .+ .+ blahblah >> my.log 2> \/dev\/null$/, @output
end
end
context "A command when standard output is nil and standard error is set" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:error => 'my_error.log', :standard => nil}
end
file
end
should "output the command with stderr directed to /dev/null" do
assert_match /^.+ .+ .+ .+ blahblah >> \/dev\/null 2>> my_error.log$/, @output
end
end
context "A command when the deprecated :cron_log is set" do
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :cron_log, "cron.log"
every 2.hours do
command "blahblah"
end
file
end
should "output the command with with the stdout and stderr going to the log" do
assert_match /^.+ .+ .+ .+ blahblah >> cron.log 2>&1$/, @output
end
end
end

View File

@ -1,20 +0,0 @@
require 'rubygems'
# Want to test the files here, in lib, not in an installed version of the gem.
$:.unshift File.expand_path(File.dirname(__FILE__) + '/../lib')
require 'whenever'
require 'shoulda'
require 'mocha'
module TestExtensions
def two_hours
"0 0,2,4,6,8,10,12,14,16,18,20,22 * * *"
end
end
class Test::Unit::TestCase
include TestExtensions
end

View File

@ -1,241 +0,0 @@
require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
class CronTest < Test::Unit::TestCase
context "When parsing time in minutes" do
should "raise if less than 1 minute" do
assert_raises ArgumentError do
parse_time(59.seconds)
end
assert_raises ArgumentError do
parse_time(0.minutes)
end
end
# For santity, do some tests on straight String
should "parse correctly" do
assert_equal '* * * * *', parse_time(1.minute)
assert_equal '0,5,10,15,20,25,30,35,40,45,50,55 * * * *', parse_time(5.minutes)
assert_equal '7,14,21,28,35,42,49,56 * * * *', parse_time(7.minutes)
assert_equal '0,30 * * * *', parse_time(30.minutes)
assert_equal '32 * * * *', parse_time(32.minutes)
assert_not_equal '60 * * * *', parse_time(60.minutes) # 60 minutes bumps up into the hour range
end
# Test all minutes
(2..59).each do |num|
should "parse correctly for #{num} minutes" do
start = 0
start += num unless 60.modulo(num).zero?
minutes = (start..59).step(num).to_a
assert_equal "#{minutes.join(',')} * * * *", parse_time(num.minutes)
end
end
end
context "When parsing time in hours" do
should "parse correctly" do
assert_equal '0 * * * *', parse_time(1.hour)
assert_equal '0 0,2,4,6,8,10,12,14,16,18,20,22 * * *', parse_time(2.hours)
assert_equal '0 0,3,6,9,12,15,18,21 * * *', parse_time(3.hours)
assert_equal '0 5,10,15,20 * * *', parse_time(5.hours)
assert_equal '0 17 * * *', parse_time(17.hours)
assert_not_equal '0 24 * * *', parse_time(24.hours) # 24 hours bumps up into the day range
end
(2..23).each do |num|
should "parse correctly for #{num} hours" do
start = 0
start += num unless 24.modulo(num).zero?
hours = (start..23).step(num).to_a
assert_equal "0 #{hours.join(',')} * * *", parse_time(num.hours)
end
end
should "parse correctly when given an 'at' with minutes as an Integer" do
assert_minutes_equals "1", 1
assert_minutes_equals "14", 14
assert_minutes_equals "27", 27
assert_minutes_equals "55", 55
end
should "parse correctly when given an 'at' with minutes as a Time" do
# Basically just testing that Chronic parses some times and we get the minutes out of it
assert_minutes_equals "1", '3:01am'
assert_minutes_equals "1", 'January 21 2:01 PM'
assert_minutes_equals "0", 'midnight'
assert_minutes_equals "59", '13:59'
end
end
context "When parsing time in days (of month)" do
should "parse correctly" do
assert_equal '0 0 * * *', parse_time(1.days)
assert_equal '0 0 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31 * *', parse_time(2.days)
assert_equal '0 0 1,5,9,13,17,21,25,29 * *', parse_time(4.days)
assert_equal '0 0 1,8,15,22 * *', parse_time(7.days)
assert_equal '0 0 1,17 * *', parse_time(16.days)
assert_equal '0 0 17 * *', parse_time(17.days)
assert_equal '0 0 29 * *', parse_time(29.days)
assert_not_equal '0 0 30 * *', parse_time(30.days) # 30 days bumps into the month range
end
should "parse correctly when given an 'at' with hours, minutes as a Time" do
# first param is an array with [hours, minutes]
assert_hours_and_minutes_equals %w(3 45), '3:45am'
assert_hours_and_minutes_equals %w(20 1), '8:01pm'
assert_hours_and_minutes_equals %w(0 0), 'midnight'
assert_hours_and_minutes_equals %w(1 23), '1:23 AM'
assert_hours_and_minutes_equals %w(23 59), 'March 21 11:59 pM'
end
should "parse correctly when given an 'at' with hours as an Integer" do
# first param is an array with [hours, minutes]
assert_hours_and_minutes_equals %w(1 0), 1
assert_hours_and_minutes_equals %w(3 0), 3
assert_hours_and_minutes_equals %w(15 0), 15
assert_hours_and_minutes_equals %w(19 0), 19
assert_hours_and_minutes_equals %w(23 0), 23
end
end
context "When parsing time in months" do
should "parse correctly" do
assert_equal '0 0 1 * *', parse_time(1.month)
assert_equal '0 0 1 1,3,5,7,9,11 *', parse_time(2.months)
assert_equal '0 0 1 1,4,7,10 *', parse_time(3.months)
assert_equal '0 0 1 1,5,9 *', parse_time(4.months)
assert_equal '0 0 1 1,6 *', parse_time(5.months)
assert_equal '0 0 1 7 *', parse_time(7.months)
assert_equal '0 0 1 8 *', parse_time(8.months)
assert_equal '0 0 1 9 *', parse_time(9.months)
assert_equal '0 0 1 10 *', parse_time(10.months)
assert_equal '0 0 1 11 *', parse_time(11.months)
assert_equal '0 0 1 12 *', parse_time(12.months)
end
should "parse correctly when given an 'at' with days, hours, minutes as a Time" do
# first param is an array with [days, hours, minutes]
assert_days_and_hours_and_minutes_equals %w(1 3 45), 'January 1st 3:45am'
assert_days_and_hours_and_minutes_equals %w(11 23 0), 'Feb 11 11PM'
assert_days_and_hours_and_minutes_equals %w(22 1 1), 'march 22nd at 1:01 am'
assert_days_and_hours_and_minutes_equals %w(23 0 0), 'march 22nd at midnight' # looks like midnight means the next day
end
should "parse correctly when given an 'at' with days as an Integer" do
# first param is an array with [days, hours, minutes]
assert_days_and_hours_and_minutes_equals %w(1 0 0), 1
assert_days_and_hours_and_minutes_equals %w(15 0 0), 15
assert_days_and_hours_and_minutes_equals %w(29 0 0), 29
end
end
context "When parsing time in days (of week)" do
should "parse days of the week correctly" do
{
'0' => %w(sun Sunday SUNDAY SUN),
'1' => %w(mon Monday MONDAY MON),
'2' => %w(tue tues Tuesday TUESDAY TUE),
'3' => %w(wed Wednesday WEDNESDAY WED),
'4' => %w(thu thurs thur Thursday THURSDAY THU),
'5' => %w(fri Friday FRIDAY FRI),
'6' => %w(sat Saturday SATURDAY SAT)
}.each do |day, day_tests|
day_tests.each do |day_test|
assert_equal "0 0 * * #{day}", parse_time(day_test)
end
end
end
should "allow additional directives" do
assert_equal '30 13 * * 5', parse_time('friday', nil, "1:30 pm")
assert_equal '22 2 * * 1', parse_time('Monday', nil, "2:22am")
assert_equal '55 17 * * 4', parse_time('THU', nil, "5:55PM")
end
should "parse weekday correctly" do
assert_equal '0 0 * * 1-5', parse_time('weekday')
assert_equal '0 0 * * 1-5', parse_time('Weekdays')
assert_equal '0 1 * * 1-5', parse_time('Weekdays', nil, "1:00 am")
assert_equal '59 5 * * 1-5', parse_time('Weekdays', nil, "5:59 am")
end
should "parse weekend correctly" do
assert_equal '0 0 * * 6,0', parse_time('weekend')
assert_equal '0 0 * * 6,0', parse_time('Weekends')
assert_equal '0 7 * * 6,0', parse_time('Weekends', nil, "7am")
assert_equal '2 18 * * 6,0', parse_time('Weekends', nil, "6:02PM")
end
end
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(:yearly)
assert_equal '@daily', parse_time(:daily)
assert_equal '@midnight', parse_time(:midnight)
assert_equal '@monthly', parse_time(:monthly)
assert_equal '@weekly', parse_time(:weekly)
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")
end
assert_raises ArgumentError do
parse_time(:reboot, nil, 5)
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)
end
end
end
private
def assert_days_and_hours_and_minutes_equals(expected, time)
cron = parse_time(2.months, 'some task', time)
minutes, hours, days, *garbage = cron.split(' ')
assert_equal expected, [days, hours, minutes]
end
def assert_hours_and_minutes_equals(expected, time)
cron = parse_time(2.days, 'some task', time)
minutes, hours, *garbage = cron.split(' ')
assert_equal expected, [hours, minutes]
end
def assert_minutes_equals(expected, time)
cron = parse_time(2.hours, 'some task', time)
assert_equal expected, cron.split(' ')[0]
end
def parse_time(time = nil, task = nil, at = nil)
Whenever::Output::Cron.new(time, task, at).time_in_cron_syntax
end
end

View File

@ -1,77 +0,0 @@
require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
class JobTest < Test::Unit::TestCase
context "A Job" do
should "return the :at set when #at is called" do
assert_equal 'foo', new_job(:at => 'foo').at
end
should "substitute the :task when #output is called" do
job = new_job(:template => ":task", :task => 'abc123')
assert_equal 'abc123', job.output
end
should "substitute the :path when #output is called" do
assert_equal 'foo', new_job(:template => ':path', :path => 'foo').output
end
should "substitute the :path with the default Whenever.path if none is provided when #output is called" do
Whenever.expects(:path).returns('/my/path')
assert_equal '/my/path', new_job(:template => ':path').output
end
end
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
end
should "output the :task if it's in double quotes" do
job = new_job(:template => '":task"', :task => 'abc123')
assert_equal %q("abc123"), job.output
end
should "output escaped single quotes in when it's wrapped in them" do
job = new_job(
:template => "before ':foo' after",
:foo => "quote -> ' <- quote"
)
assert_equal %q(before 'quote -> '\'' <- quote' after), job.output
end
should "output escaped double quotes when it's wrapped in them" do
job = new_job(
:template => 'before ":foo" after',
:foo => 'quote -> " <- quote'
)
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
def new_job(options={})
Whenever::Job.new(options)
end
end

View File

@ -1,31 +0,0 @@
# -*- 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.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"
end