Gem 有人用过 clockwork 吗,怎么在 production 环境下启动?

danjiang · 2016年05月25日 · 最后由 danjiang 回复于 2016年08月02日 · 2136 次阅读

clockwork https://github.com/tomykaira/clockwork

服务器环境运行下面的命令都不行,报错仍是 development

bin/clockwork clock.rb -e production
bin/clockwork clock.rb RAILS_ENV=production

本地的开发环境执行下面的命令,没有任何问题

bin/clockwork clock.rb

clock.rb 文件的代码

require 'clockwork'
require_relative './config/boot'
require_relative './config/environment'

module Clockwork
    every(1.day, 'solr.indexing', :at => '02:00') { SolrIndexingJob.perform_later }
end

这个 gem 有点 bug,执行完操作,数据库连接不会释放。所以得手动释放. 环境问题可以在配置文件顶部配置. 我生产环境用的配置如下。

ENV["RAILS_ENV"]='production'
require File.expand_path('../config/boot', __FILE__)
require File.expand_path('../config/environment', __FILE__)
Dir[File.expand_path("../lib/*.rb", __FILE__)].each {|file| require file }
module Clockwork
  configure do |config|
    config[:sleep_timeout] = 5
    config[:logger] = Logger.new(File.join(Rails.root,'log/clockwork.log'))
    config[:max_threads] = 15
    config[:thread] = true
  end

  error_handler do |e|
    ExceptionNotifier.notify_exception(e)
  end

  def self.wrapper(message)
    logger = ->(mes) do
      `echo #{Time.now.to_s} #{mes} >> #{File.join(Rails.root,'log/clockwork.log')}`
    end
    begin
      start_time = Time.now
      logger.call message + '开始'
      yield
      end_time = Time.now
      duration = ((end_time - start_time)/60).round(1)
      logger.call message + "结束,用时#{duration}分钟"
    ensure
      ActiveRecord::Base.clear_active_connections!
    end
  end

  every(1.hours, 'stub.job') do
    puts 'clockwork is running.current time is ' + Time.now.to_s
  end

  every(1.day, 'get_test_data', :at => '01:00') do
    Clockwork.wrapper('测试') do
      Food.foo_ceshi
    end
  end


end

需要 登录 后方可回复, 如果你还没有账号请 注册新账号