ruby Rails中自定义rake任务

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby Rails中自定义rake任务相关的知识,希望对你有一定的参考价值。

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

以上是关于ruby Rails中自定义rake任务的主要内容,如果未能解决你的问题,请参考以下文章

在 rake 任务中使用 rails logger,rails 5

如何在 ruby​​ on rails 的亚马逊 aws 服务器中使用 gem 执行 rake 任务?

ruby 使用rake任务管理Rails应用程序版本号(包括git-flow支持)

Rails Guide -- Ruby on Rake

Ruby on Rails:运行 rake 命令时出现错误消息

在rals中将rake任务迁移到Lambda