使用whenever gem代替 crontab !!!
访问量: 4280
在一个项目中,会有很多情况要用到crontab,最常见的是:
1. 定时备份数据库
2. 定时删除无用的日志。
使用 crontab 的话,需要这样写:
0 * * * * /bin/bash -l -c 'cd /home/sg552/workspace/babble_porta .....可读性很差。
而如果使用whenever 的话,就可以弄的非常优雅: Whenever is a Ruby gem that provides a clear syntax for writing and deploying cron jobs.
1. 安装(Installation ) : $ gem install whenever 或者: Or with Bundler in your Gemfile.gem 'whenever', :require => false2. 建立对应的文件config/schedule.rb : ( create config file)
$ cd /apps/my-great-project $ wheneverize .This will create an initial config/schedule.rb file for you.
# config/schedule.rb every 5.minutes do runner "UserWatchedRepo.update" end # in another file, we defined the 'runner'. class UserWatchedRepo def update # do something end end3. 然后,我们可以查看他生成的crontab: ( let's check what content it generated ) 内容仅供参考
sg552@siwei-moto:~/workspace/babble_portal$ whenever 0 0 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31 * * /bin/bash -l -c 'cd /home/sg552/workspace/babble_portal && RAILS_ENV=production bundle exec rake .................................... ## [message] Above is your schedule file converted to cron syntax; your crontab file was not updated. ## [message] Run `whenever --help' for more options.
4. 最后,让这个crontab 生效: (at last, let's make it to take effect )
sg552@siwei-moto:~/workspace/babble_portal$ whenever --update-crontab [write] crontab file updated
末尾,语法参考,几个区别: ( differences between command, runner and rake)
command : 用的是最纯粹的shell command. 例如 : 'touch /tmp/some_file" ( a shell command)
runner : 用的是Ruby的类,例如: SomeClass.some_method ( a ruby's method call)
rake : 用的是rake 命令。 ( a rake task )