ruby Foreman在整个过程结束后终止,并且不会按照Procfile中的定义相应地运行

yquaqz18  于 2023-08-04  发布在  Ruby
关注(0)|答案(2)|浏览(102)

我正在将数据从基于Web的CSV导入数据库,因此我创建了一个将数据导入数据库的rake任务。然而,我试图让我的rails应用程序运行起来更无缝,我将import rake taskrunning rails server集成到foreman中。
但是,当我运行foreman start时,进程启动,但在rake任务完成后终止。我还希望在运行rails s之前先启动rake任务
下面是我所做的:

lib/tasks/web_import.rake

require 'open-uri'
require 'csv'

namespace :web_import do
  desc 'Import users from csv'

  task users: :environment do
    url = 'http://blablabla.com/content/people.csv'
    # I forced encoding so avoid UndefinedConversionError "\xC3" from ASCII-8BIT to UTF-8
    csv_string = open(url).read.force_encoding('UTF-8')

    counter = 0
    duplicate_counter = 0

    user = []
    CSV.parse(csv_string, headers: true, header_converters: :symbol) do |row|
      next unless row[:name].present? && row[:email_address].present?
      user = CsvImporter::User.create row.to_h
      if user.persisted?
        counter += 1
      else
        duplicate_counter += 1
      end
    end
    p "Email duplicate record: #{user.email_address} - #{user.errors.full_messages.join(',')}" if user.errors.any?

    p "Imported #{counter} users, #{duplicate_counter} duplicate rows ain't added in total"
  end
end

字符串

Procfile

rake: rake web_import:users
server: rails s

我运行forman start时,下图显示了进程

x1c 0d1x的数据
我想在foreman中的rake任务在运行rails s命令之前首先运行。我也不希望它自己结束。我不知道我做错了什么。
任何帮助都是感激的。

3z6pesqy

3z6pesqy1#

我通过重构Procfile解决了这个问题。我没有使用两个任务,而是使用&&将其合并为一个命令,这样就可以确定哪个命令使用前缀,哪个命令使用后缀。
所以我把配置文件改成:

tasks: rake web_import:users && rails s -p 3000

字符串
这样,我就先运行import命令,最后运行server命令。
如果你注意到了,我用-p flap添加了端口,这样就不会确保服务器正在监听端口3000。注意添加端口是可选的。
我希望这对某人也有帮助。

bzzcjhmw

bzzcjhmw2#

&& until ! sleep 1; do sleep 1; done添加到任何退出的Procfile命令的末尾,从而强制终止Profile的所有进程。
换句话说,您将永远保持运行该命令的“进程”。这并不理想,但是对于本地开发,您需要一些命令来运行,完成运行,但不能退出Procfile的监督,它可以工作。
这里是我的procfile的一个示例片段,我将示例配置文件复制到我的redis sentinel进程需要它们存在的位置。

redis-sentinel-config: cp -f spec/support/config/redis/sentinel1.EXAMPLE.conf spec/support/config/redis/sentinel1.conf && cp -f spec/support/config/redis/sentinel2.EXAMPLE.conf spec/support/config/redis/sentinel2.conf && cp -f spec/support/config/redis/sentinel3.EXAMPLE.conf spec/support/config/redis/sentinel3.conf && until ! sleep 1; do sleep 1; done
redis-senitnel1: sleep 1 && redis-server spec/support/config/redis/sentinel1.conf --sentinel
redis-senitnel2: sleep 1 && redis-server spec/support/config/redis/sentinel2.conf --sentinel
redis-senitnel3: sleep 1 && redis-server spec/support/config/redis/sentinel3.conf --sentinel

字符串

相关问题