JiangYongKang
7/31/2018 - 2:29 PM

Rails 中自定义 rake task

namespace :server do

  logger = Logger.new(STDOUT)
  server_pid_file = "#{Rails.root}/tmp/pids/server.pid"

  desc 'start web server'
  task start: 'environment' do
    logger.info 'trying to start web server ...'
    system "bundle exec rails s -p 3000 -d"
    sleep(2)
    logger.info "web server started pid is: #{File.readlines(server_pid_file).first}."
    logger.info 'web server started successfully.'
  end

  desc 'stop web server'
  task stop: 'environment' do
    logger.info 'trying to stop web server ...'
    if File.exist?(server_pid_file)
      logger.info "stopping web server now pid is: #{File.readlines(server_pid_file).first}"
      system "pumactl stop -P #{server_pid_file}"
      logger.info 'web server stop successfully.'
    else
      logger.info 'web server not running!'
    end
  end

  desc 'restart web server'
  task restart: 'environment' do
    logger.info 'trying to restart web server ...'
    Rake::Task['server:stop'].invoke
    Rake::Task['server:start'].invoke
    logger.info "web server restart successfully."
  end
end
namespace :sidekiq do

  logger = Logger.new(STDOUT)
  sidekiq_pid_file = "#{Rails.root}/tmp/pids/sidekiq.pid"

  desc 'sidekiq start'
  task start: 'environment' do
    logger.info 'trying to start sidekiq ...'
    system "bundle exec sidekiq -C config/sidekiq.yml -P tmp/pids/sidekiq.pid -d -L log/sidekiq.log"
    sleep(2)
    logger.info "sidekiq started pid is: #{File.readlines(sidekiq_pid_file).first}."
    logger.info 'sidekiq started successfully.'
  end

  desc 'sidekiq stop'
  task stop: 'environment' do
    logger.info 'trying to stop sidekiq ...'
    if File.exist?(sidekiq_pid_file)
      logger.info "stopping sidekiq now pid is: #{File.readlines(sidekiq_pid_file).first}"
      system "sidekiqctl stop #{sidekiq_pid_file}"
      logger.info 'sidekiq stop successfully.'
    else
      logger.info 'sidekiq not running!'
    end
  end

  desc "sidekiq restart"
  task restart: 'environment' do
    logger.info 'trying to restart sidekiq ...'
    Rake::Task['sidekiq:stop'].invoke
    Rake::Task['sidekiq:start'].invoke
    logger.info "sidekiq restart successfully."
  end

end