Compare commits

..

81 Commits

Author SHA1 Message Date
John Bintz
905558da45 check instead to see if stdin is not a tty for triggering pipe 2011-09-06 09:30:12 -04:00
John Bintz
919dbe09ef allow piping of crontab from stdin to stdout 2011-08-19 11:40:23 -04:00
Javan Makhmali
ace7f086a9 replaced another confusing 'app' dir 2011-07-31 23:47:30 -04:00
Javan Makhmali
e6015b5f64 Merge pull request #154 from andrew/master
Default the wheneverize commands directory option to .
2011-07-31 11:55:21 -07:00
Javan Makhmali
ab877e3cbb improve eval'ing of schedule file to reveal the filename in backtraces 2011-07-31 14:16:23 -04:00
Javan Makhmali
8bb0f04131 formatting 2011-07-31 09:33:16 -04:00
Javan Makhmali
15d91a3efd prefer autoload to require 2011-07-31 09:27:18 -04:00
Javan Makhmali
16f988f47d avoid confusion with 'app' directory 2011-07-30 19:08:41 -04:00
Javan Makhmali
648587b416 Merge pull request #158 from szajbus/master
Run rake through bundle exec
2011-07-19 06:20:18 -07:00
Michał Szajbe
439a13644c run rake through bundler if possible 2011-07-19 10:19:13 +02:00
Michał Szajbe
b405def424 encapsulate rails 3 check for easier testing 2011-07-19 10:18:33 +02:00
Andrew Nesbitt
f21f48a215 Default wheneverize directory to '.' 2011-07-11 11:11:07 +01:00
Javan Makhmali
42061be142 removed stray text from readme 2011-07-07 08:50:32 -04:00
Javan Makhmali
660fbc50e3 update readme for syntax highlighting 2011-07-04 10:04:27 -04:00
Javan Makhmali
4c242cf0c5 Merge pull request #153 from biow0lf/master
Fix typo
2011-07-04 06:40:09 -07:00
Igor Zubkov
820d34a86a Fix typo 2011-07-04 11:26:22 +03:00
Javan Makhmali
8515ffb528 added compatibility note to readme 2011-06-19 14:19:55 -04:00
Javan Makhmali
7ca2d87823 moved license 2011-06-19 14:17:01 -04:00
Javan Makhmali
a4a41704eb removed incompatible rubies 2011-06-19 14:13:23 -04:00
Javan Makhmali
b4ed6373cf added .travis.yml 2011-06-19 13:54:27 -04:00
Javan Makhmali
a9eede25cf i18n that is 2011-06-19 10:30:09 -04:00
Javan Makhmali
1f58338d6b add i18n to gemspec 2011-06-19 10:28:54 -04:00
Javan Makhmali
89c9148383 add rake to dev dependencies, add travis-ci status to readme 2011-06-19 10:14:45 -04:00
Javan Makhmali
bf679b02a9 Merge pull request #138 from cgriego/master
Capistrano tasks enhancements
2011-06-14 06:47:30 -07:00
Javan Makhmali
3f9dda27a9 Merge pull request #145 from jdutil/patch-1
RVM gotcha directions to the README
2011-06-12 08:19:21 -07:00
Javan Makhmali
0114f82e1c Merge pull request #148 from markisisme/master
Add quotes to --set example.
2011-06-12 08:18:33 -07:00
Mark
fed71a5574 Add quotes to --set example. 2011-06-09 11:53:58 -07:00
Javan Makhmali
01c27c9c10 smoke the latest chronic 2011-06-08 21:24:06 -04:00
Jeff Dutil
7be0626800 I am adding RVM gotcha directions to the README since I ran into the same issue as another user https://github.com/javan/whenever/issues/110 and thought at first it may be related to Whenever. The wiki may be a good place for this instruction, but I find it much more useful / easier to find in the README. The wikis homepage doesn't link to the relevant page, and it could be difficult for users to find (as it was for me). 2011-05-31 18:23:59 -07:00
Chris Griego
98ae96a2af Capistrano enhancements
* Use fetch(:variable) to avoid collisions with namespaces
* Default :whenever_environment to the :rails_env variable
* Document the Capistrano tasks
* Apply whenever_roles at runtime so the variable can be set after the recipe is loaded
* Add transaction rollback support to the update_crontab task
2011-05-24 23:54:34 -05:00
Javan Makhmali
1214114c40 bump version 2011-05-24 22:12:32 -04:00
Javan Makhmali
56ab2cba32 require thread 2011-05-24 22:07:14 -04:00
Javan Makhmali
5f7253ccc3 Output no update message as comments. 2011-05-24 22:01:31 -04:00
Javan Makhmali
cc6bafb37a allow comma in raw cron syntax 2011-05-23 22:23:42 -04:00
Javan Makhmali
78786a4465 Merge pull request #128 from amiryal/master
Undocumented change in lib/whenever/capistrano.rb
2011-05-23 18:10:56 -07:00
Javan Makhmali
1654f67774 convert most shortcuts to seconds 2011-05-23 21:08:43 -04:00
Amir Yalon
6f94747ebd Fix documentation for Capistrano with different environments 2011-04-04 18:04:39 +03:00
Javan Makhmali
a3b5791bbb Whenever v0.6.7 2011-03-23 22:09:21 -04:00
Javan Makhmali
6305ab0d8e removed -i from default job_template 2011-03-23 22:03:43 -04:00
Jeremy Lingmann
3cf92a44c2 Require that the comment identifiers are always on a line by themselves, but allow for whitespace after the identifier. 2011-03-10 22:30:11 -08:00
Jeremy Lingmann
971854528b Revert "Don't anchor the regexp to EOL to fix matching issues that were causing the entire block of crontab entries to appear twice in the crontab. This could be due to the way cron is adding newlines or some other post-processing that occurs on the cron. This bug was reproduced in the following environment: Ubuntu 10.04.2 LTS, rvm 1.0.14, ruby 1.8.7 patchlevel 253, capistrano 2.5.19, capistrano-ext 1.2.1, bundler 1.0.10"
This reverts commit 1f11510d87.
2011-03-10 22:00:41 -08:00
Jeremy Lingmann
7dd0a046ae Fixing issue with prepare method. The issue was that [stripped_contents.length..-1] was not capturing the trailing contents as expected. Instead it was grabbing the last 2 characters of my identifier block and then tacking those 2 characters back on to the end. In short, .length and the range operator are not behaving consistently on the input. 2011-03-10 21:50:50 -08:00
Jeremy Lingmann
1f11510d87 Don't anchor the regexp to EOL to fix matching issues that were causing the entire block of crontab entries to appear twice in the crontab. This could be due to the way cron is adding newlines or some other post-processing that occurs on the cron. This bug was reproduced in the following environment: Ubuntu 10.04.2 LTS, rvm 1.0.14, ruby 1.8.7 patchlevel 253, capistrano 2.5.19, capistrano-ext 1.2.1, bundler 1.0.10 2011-03-10 18:06:43 -08:00
Javan Makhmali
96fc6eb4dc fix unclosed identifier bug. #119 2011-03-08 19:47:43 -06:00
Javan Makhmali
8ef9e26109 release v0.6.5 2011-03-08 10:47:55 -06:00
Javan Makhmali
53c0a4d36d readme 2011-03-08 10:31:56 -06:00
Javan Makhmali
2a89d79a28 Ditched Jeweler in favor of a self-managed gemspec with the Bundler helpers. 2011-03-06 21:32:49 -05:00
Javan Makhmali
bbd5bcf782 readme 2011-03-06 21:15:47 -05:00
Javan Makhmali
59e7c31093 add message when just outputting schedule file 2011-03-06 21:10:03 -05:00
Javan Makhmali
a94dda4b8b allow raw cron sytanx 2011-03-06 17:31:17 -05:00
Javan Makhmali
6b69ebd10f added :whenever_environment to cap task for easier multistage support 2011-03-06 16:39:52 -05:00
Javan Makhmali
4b98f064eb add -i to the bash job template 2011-03-06 16:17:36 -05:00
Javan Makhmali
006a1d963b Merge branch 'master' of https://github.com/teejayvanslyke/whenever into teejayvanslyke-master 2011-03-06 16:11:49 -05:00
teejayvanslyke
fe022bb1c6 Setting nil or blank environment variables now properly formats output
as ENVVAR="" instead of ENVVAR=.
2010-12-07 10:12:08 -08:00
Rich Meyers
d0a7a8600e Test for issue #95 - terminating newlines should be preserved when updating crontab files 2010-11-02 12:32:45 -04:00
Rich Meyers
c4abbefe00 Preserve whitespace at the end of crontab contents (issue #95) 2010-11-01 17:07:09 -04:00
Javan Makhmali
ca10a69e83 Release v0.6.2 2010-10-26 10:41:01 -04:00
Javan Makhmali
46da1bc6f8 converted rdoc files to markdown 2010-10-26 10:30:17 -04:00
Javan Makhmali
974b5a2016 job type defaults are now in setup.rb 2010-10-26 09:59:24 -04:00
Javan Makhmali
9f73bcb469 set environment and path earlier so schedule files do conditionals with them 2010-10-25 21:14:45 -04:00
Javan Makhmali
b255926e05 Don't leave Whenever comments when clearing 2010-10-25 21:04:17 -04:00
Javan Makhmali
20faaa266d Don't leave Whenever comments when clearing 2010-10-25 21:03:49 -04:00
Javan Makhmali
2060cb95fa removed base.rb 2010-10-25 20:41:57 -04:00
Javan Makhmali
2d54a8905a Regenerated gemspec for version 0.6.1 2010-10-20 17:39:50 -04:00
Javan Makhmali
395bcf6955 bad release; trying again.. 2010-10-20 17:39:39 -04:00
Javan Makhmali
958d0a8942 fixed dup in README 2010-10-20 17:36:40 -04:00
Javan Makhmali
acb15cd4ea Regenerated gemspec for version 0.6.0 2010-10-20 17:35:00 -04:00
Javan Makhmali
645a4af994 Releasing v0.6.0 with better Rails 3 and RVM support. 2010-10-20 17:34:36 -04:00
Javan Makhmali
3e7e7f1401 fixed conflict 2010-10-20 17:13:09 -04:00
Javan Makhmali
e66226e3ae created a new :job_template to wrap all commands with. using 'bash -l -c' by default now to load the entire enviroment which should help with RVM issues. 2010-10-20 17:12:00 -04:00
Javan Makhmali
2effe0b32d fixed conflict 2010-10-19 17:50:40 -04:00
Javan Makhmali
ff0d68af55 don't worry about preserving the Rails 2 runner job_type if this is a Rails 3 app 2010-10-19 17:37:10 -04:00
Javan Makhmali
953987c6b2 moved output redirection to the Job class and subing it in from the job templates 2010-10-19 13:53:41 -04:00
Javan Makhmali
4e0c357f4d check if runner is defined before aliasing it 2010-10-19 09:19:34 -04:00
Javan Makhmali
436255e4a5 added a built-in capistrano recipe 2010-10-18 18:51:27 -04:00
Javan Makhmali
0055c36aef runners for Rails 3 2010-10-18 12:08:28 -04:00
Javan Makhmali
e7e4a37b3a drop /usr/bin/env from rake job - let PATH do the work. added --silent flag to rake job tosupress the 'in directory' message. 2010-10-18 10:41:00 -04:00
Javan Makhmali
3ad1e30561 allow identifier for writes. fix fight over -c 2010-09-27 18:21:21 -04:00
Javan Makhmali
9c96e7c16b Fixed regex related bugs. Release v0.5.3 2010-09-24 13:41:05 -04:00
Javan Makhmali
a3d2da903d Release v0.5.2 2010-09-15 22:21:54 -04:00
Javan Makhmali
119f26c08e use aaronh-chronic which is ruby 1.9.2 compatible 2010-09-15 22:05:47 -04:00
32 changed files with 938 additions and 527 deletions

1
.gitignore vendored
View File

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

3
.gitmodules vendored
View File

@ -1,3 +0,0 @@
[submodule "lib/whenever/vendor/gems/chronic"]
path = lib/whenever/vendor/gems/chronic
url = git://github.com/AaronH/chronic.git

7
.travis.yml Normal file
View File

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

View File

@ -1,4 +1,77 @@
== 0.5.0 / June 28th, 2010
### 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)]
@ -7,7 +80,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]
@ -18,49 +91,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]
@ -69,22 +142,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]
@ -97,6 +170,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]

4
Gemfile Normal file
View File

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

22
LICENSE Normal file
View File

@ -0,0 +1,22 @@
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 Normal file
View File

@ -0,0 +1,163 @@
### 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,127 +0,0 @@
== 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,34 +1,11 @@
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 '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 '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 :test => :check_dependencies
test.libs << 'lib' << 'test'
test.pattern = 'test/{functional,unit}/**/*_test.rb'
test.verbose = true
end
task :default => :test

20
bin/whenever Normal file → Executable file
View File

@ -3,33 +3,37 @@
require 'rubygems'
require 'optparse'
require 'whenever'
require 'whenever/version'
options = Hash.new
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: whenever [options]"
opts.on('-v', '--version') { puts "Whenever v#{Whenever::VERSION}"; exit(0) }
opts.on('-w', '--write-crontab') { options[:write] = true }
opts.on('-c', '--cut [lines]', 'Cut lines from the top of the cronfile') do |lines|
options[:cut] = lines.to_i if lines
end
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('-s', '--set [variables]', 'Example: --set environment=staging&path=/my/sweet/path') do |set|
options[:set] = set if set
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)

19
bin/wheneverize Normal file → Executable file
View File

@ -17,17 +17,16 @@ OptionParser.new do |opts|
end
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."
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.
#
@ -52,7 +51,7 @@ content = <<-FILE
FILE
file = 'config/schedule.rb'
base = ARGV.shift
base = ARGV.empty? ? '.' : ARGV.shift
file = File.join(base, file)
if File.exists?(file)

View File

@ -1,14 +1,30 @@
require 'chronic'
require 'active_support/all'
require 'thread'
# Bundling in http://github.com/AaronH/chronic because
# it's compatible with Ruby 1.9.2 and the official
# gem isn't. I hope to remove this eventually.
require 'whenever/vendor/gems/chronic/lib/chronic'
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
require 'whenever/base'
require 'whenever/job_list'
require 'whenever/job'
require 'whenever/cron'
require 'whenever/output_redirection'
require 'whenever/command_line'
require 'whenever/version'
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,11 +0,0 @@
module Whenever
def self.cron(options)
Whenever::JobList.new(options).generate_cron_output
end
def self.path
Dir.pwd
end
end

View File

@ -0,0 +1,62 @@
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,7 +3,6 @@ require 'tempfile'
module Whenever
class CommandLine
def self.execute(options={})
new(options).run
end
@ -30,7 +29,6 @@ module Whenever
exit(1)
end
@options[:cut] = @options[:cut].to_i
end
def run
@ -40,6 +38,8 @@ 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,61 +51,90 @@ module Whenever
end
def whenever_cron
@whenever_cron ||= [comment_open, (Whenever.cron(@options) unless @options[:clear]), comment_close].compact.join("\n") + "\n"
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 = ['crontab -l']
command << "-u #{@options[:user]}" if @options[:user]
command_results = %x[#{command.join(' ')} 2> /dev/null]
@current_crontab = $?.exitstatus.zero? ? prepare(command_results) : ''
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)
tmp_cron_file = Tempfile.new('whenever_tmp_cron').path
File.open(tmp_cron_file, File::WRONLY | File::APPEND) do |file|
file << contents
end
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
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}"
if !stdin.tty?
exit(0)
else
warn "[fail] Couldn't write crontab; try running `whenever' with no options to ensure your schedule file is valid."
exit(1)
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
def updated_crontab
# Check for unopened or unclosed identifier blocks
if read_crontab.index(comment_open) && !read_crontab.index(comment_close)
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.index(comment_open) && read_crontab.index(comment_close)
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.index(comment_open) && read_crontab.index(comment_close)
read_crontab.gsub(Regexp.new("#{comment_open}.+#{comment_close}", Regexp::MULTILINE), whenever_cron.chomp)
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
end.gsub(/\n{3,}/, "\n\n") # More than two newlines becomes just two.
end
#
def prepare(contents)
contents.split("\n")[@options[:cut]..-1].join("\n")
# 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
@ -120,5 +149,12 @@ module Whenever
"# End #{comment_base}"
end
def stdin
$stdin
end
def stdout
$stdout
end
end
end

View File

@ -1,19 +1,24 @@
module Whenever
module Output
class Cron
REGEX = /^.+ .+ .+ .+ .+.?$/
attr_accessor :time, :task
def initialize(time = nil, task = nil, at = nil, output_redirection = nil)
def initialize(time = nil, task = nil, at = 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)
def self.enumerate(item, detect_cron = true)
if item and item.is_a?(String)
items = item.split(',')
items =
if detect_cron && item =~ REGEX
[item]
else
item.split(',')
end
else
items = item
items = [items] unless items and items.respond_to?(:each)
@ -23,42 +28,48 @@ module Whenever
def self.output(times, job)
enumerate(times).each do |time|
enumerate(job.at).each do |at|
yield new(time, job.output, at, job.output_redirection).output
enumerate(job.at, false).each do |at|
yield new(time, job.output, at).output
end
end
end
def output
[time_in_cron_syntax, task, output_redirection].compact.join(' ').strip
[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
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, :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'
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
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
@ -131,7 +142,6 @@ module Whenever
output[0, max_occurances].join(',')
end
end
end
end

View File

@ -1,21 +1,28 @@
module Whenever
class Job
attr_reader :at, :output_redirection
attr_reader :at
def initialize(options = {})
@options = options
@at = options[:at]
@output_redirection = options.has_key?(:output) ? options[:output] : :not_set
@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
@options[:template].dup.gsub(/:\w+/) do |key|
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]
option = options[key.sub(':', '').to_sym]
if before_and_after.all? { |c| c == "'" }
escape_single_quotes(option)
@ -26,8 +33,6 @@ module Whenever
end
end
end
protected
def escape_single_quotes(str)
str.gsub(/'/) { "'\\''" }
@ -36,6 +41,5 @@ module Whenever
def escape_double_quotes(str)
str.gsub(/"/) { '\"' }
end
end
end

View File

@ -1,31 +1,27 @@
module Whenever
class JobList
def initialize(options)
@jobs, @env, @set_variables = {}, {}, {}
@jobs, @env, @set_variables, @pre_set_variables = {}, {}, {}, {}
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])
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
# 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)
instance_eval(setup + schedule, options[:file] || '<eval>')
end
def set(variable, value)
return if instance_variable_defined?("@#{variable}".to_sym)
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)
@ -59,9 +55,7 @@ module Whenever
end
end
def generate_cron_output
set_path_environment_variable
def generate_cron_output
[environment_variables, cron_jobs].compact.join
end
@ -79,29 +73,20 @@ module Whenever
pairs.each do |pair|
next unless pair.index('=')
variable, value = *pair.split('=')
set(variable.strip.to_sym, value.strip) unless variable.blank? || value.blank?
unless variable.blank? || value.blank?
variable = variable.strip.to_sym
set(variable, value.strip)
@pre_set_variables[variable] = value
end
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}\n"
output << "#{key}=#{val.blank? ? '""' : val}\n"
end
output << "\n"
@ -156,6 +141,5 @@ module Whenever
shortcut_jobs.join + combine(regular_jobs).join
end
end
end

View File

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

View File

@ -1,59 +1,55 @@
module Whenever
module Output
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
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 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
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
def redirect_from_string
">> #{@output} 2>&1"
end
end
end

24
lib/whenever/setup.rb Normal file
View File

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

@ -1 +0,0 @@
Subproject commit d027ad09333ac49e9eb368c659c5243b515a7694

View File

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

View File

@ -65,8 +65,6 @@ 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
@ -79,38 +77,61 @@ 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 delete" do
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 "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
should "clear an existing block if the identifier matches" do
existing = <<-EXISTING_CRON
# Something
@ -124,20 +145,17 @@ 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
@ -179,6 +197,7 @@ 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
@ -196,6 +215,7 @@ 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
@ -213,6 +233,7 @@ 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
@ -230,6 +251,7 @@ 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
@ -259,8 +281,7 @@ My whenever job that was already here
# End Whenever generated tasks for: My identifier
EXISTING_CRON
# here-doc adds an extra newline we need removed
assert_equal existing.strip, @command.send(:prepare, existing)
assert_equal existing, @command.send(:prepare, existing)
end
should "trim off the top lines of the file" do
@ -280,8 +301,61 @@ My whenever job that was already here
# End Whenever generated tasks for: My identifier
NEW_CRON
# here-doc adds an extra newline we need removed
assert_equal new_cron.strip, @command.send(:prepare, existing)
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

View File

@ -6,6 +6,7 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every "weekday", :at => '5:02am' do
command "blahblah"
end
@ -21,6 +22,7 @@ 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
@ -37,6 +39,7 @@ 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
@ -53,6 +56,7 @@ 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
@ -68,6 +72,7 @@ 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
@ -83,6 +88,7 @@ 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"
@ -99,6 +105,7 @@ 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"
@ -107,7 +114,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 /usr/bin/env rake blah:blah', @output
assert_match '2 5,15 * * 1,3,5 cd /your/path && RAILS_ENV=production bundle exec rake blah:blah --silent', @output
end
end
@ -115,6 +122,7 @@ 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
@ -138,6 +146,7 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every :reboot do
command "command_1"
command "command_2"
@ -155,8 +164,9 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/your/path'
every :day do
every :daily do
rake "blah:blah"
runner "runner_1"
command "command_1"
@ -167,7 +177,7 @@ class OutputAtTest < Test::Unit::TestCase
end
should "output all of the commands @daily" do
assert_match '@daily cd /your/path && RAILS_ENV=production /usr/bin/env rake blah:blah', @output
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
@ -179,6 +189,7 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 5.minutes, :at => 1 do
command "blahblah"
end
@ -194,6 +205,7 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 4.minutes, :at => 2 do
command "blahblah"
end
@ -209,6 +221,7 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 3.minutes, :at => 7 do
command "blahblah"
end
@ -224,6 +237,7 @@ class OutputAtTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
every 2.minutes, :at => 27 do
command "blahblah"
end
@ -234,4 +248,21 @@ 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,10 +4,11 @@ class OutputDefaultDefinedJobsTest < Test::Unit::TestCase
# command
context "A plain command" do
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
@ -19,12 +20,64 @@ 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'
@ -41,6 +94,7 @@ 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'
@ -53,12 +107,31 @@ class OutputDefaultDefinedJobsTest < Test::Unit::TestCase
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"
@ -67,7 +140,25 @@ 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 /usr/bin/env rake blahblah', @output
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
@ -75,6 +166,7 @@ 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'
@ -83,7 +175,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 /usr/bin/env rake blahblah', @output
assert_match two_hours + ' cd /some/other/path && RAILS_ENV=production bundle exec rake blahblah --silent', @output
end
end

View File

@ -6,6 +6,7 @@ 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"
@ -22,6 +23,7 @@ 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'
@ -38,6 +40,7 @@ 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
@ -55,6 +58,7 @@ 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
@ -72,6 +76,7 @@ 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'
@ -86,10 +91,11 @@ class OutputDefinedJobTest < Test::Unit::TestCase
context "A defined job that uses a :path where none is explicitly set" do
setup do
Whenever.expects(:path).returns('/my/path')
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'

View File

@ -8,6 +8,8 @@ class OutputEnvTest < Test::Unit::TestCase
<<-file
env :MYVAR, 'blah'
env 'MAILTO', "someone@example.com"
env :BLANKVAR, ''
env :NILVAR, nil
file
end
@ -18,39 +20,14 @@ class OutputEnvTest < Test::Unit::TestCase
should "output MAILTO environment variable" do
assert_match "MAILTO=someone@example.com", @output
end
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 ""
should "output BLANKVAR environment variable" do
assert_match "BLANKVAR=\"\"", @output
end
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
should "output NILVAR environment variable" do
assert_match "NILVAR=\"\"", @output
end
end
end
end

View File

@ -6,6 +6,7 @@ class OutputRedirectionTest < Test::Unit::TestCase
setup do
@output = Whenever.cron \
<<-file
set :job_template, nil
set :output, nil
every 2.hours do
command "blahblah"
@ -23,6 +24,7 @@ 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"
@ -39,6 +41,7 @@ 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
@ -54,6 +57,7 @@ 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'
@ -71,6 +75,7 @@ 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' }
@ -88,6 +93,7 @@ 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
@ -105,6 +111,7 @@ 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"
@ -122,6 +129,7 @@ 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"
@ -138,6 +146,7 @@ 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"
@ -154,6 +163,7 @@ 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"
@ -170,6 +180,7 @@ 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
@ -185,6 +196,7 @@ 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
@ -200,6 +212,7 @@ 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
@ -215,6 +228,7 @@ 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
@ -230,6 +244,7 @@ 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
@ -245,6 +260,7 @@ 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
@ -260,6 +276,7 @@ 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
@ -275,6 +292,7 @@ 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,20 +174,26 @@ 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(:year)
assert_equal '@annually', parse_time(:annually)
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 '@hourly', parse_time(:hour)
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(:hour, nil, "1:00 am")
parse_time(:hourly, nil, "1:00 am")
end
assert_raises ArgumentError do
@ -195,7 +201,16 @@ class CronTest < Test::Unit::TestCase
end
assert_raises ArgumentError do
parse_time(:day, nil, '4:20pm')
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

View File

@ -7,14 +7,6 @@ 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
@ -32,7 +24,6 @@ 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
@ -59,6 +50,23 @@ 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,78 +1,31 @@
# 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 = %q{whenever}
s.version = "0.5.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Javan Makhmali"]
s.date = %q{2010-06-28}
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/job.rb",
"lib/whenever/job_list.rb",
"lib/whenever/job_types/default.rb",
"lib/whenever/outputs/cron.rb",
"lib/whenever/outputs/cron/output_redirection.rb",
"lib/whenever/version.rb",
"test/command_line_test.rb",
"test/cron_test.rb",
"test/output_at_test.rb",
"test/output_command_test.rb",
"test/output_defined_job_test.rb",
"test/output_env_test.rb",
"test/output_rake_test.rb",
"test/output_redirection_test.rb",
"test/output_runner_test.rb",
"test/test_helper.rb",
"whenever.gemspec"
]
s.homepage = %q{http://github.com/javan/whenever}
s.rdoc_options = ["--charset=UTF-8"]
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.rubygems_version = %q{1.3.6}
s.summary = %q{Clean ruby syntax for defining and deploying messy cron jobs.}
s.test_files = [
"test/command_line_test.rb",
"test/cron_test.rb",
"test/output_at_test.rb",
"test/output_command_test.rb",
"test/output_defined_job_test.rb",
"test/output_env_test.rb",
"test/output_rake_test.rb",
"test/output_redirection_test.rb",
"test/output_runner_test.rb",
"test/test_helper.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<chronic>, [">= 0.2.3"])
else
s.add_dependency(%q<chronic>, [">= 0.2.3"])
end
else
s.add_dependency(%q<chronic>, [">= 0.2.3"])
end
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