Ruby on rails 如何从rails中的控制器调用rake任务
我在Ruby on rails 如何从rails中的控制器调用rake任务,ruby-on-rails,rake,Ruby On Rails,Rake,我在/lib/tasks/scriping.rake namespace :scriping do task :list => :environment do client = CloudscrapeClient.new Robot.all.each do |robot| execution_id = client.runs(robot.list_run_id).execute(connect: true) e
/lib/tasks/scriping.rake
namespace :scriping do
task :list => :environment do
client = CloudscrapeClient.new
Robot.all.each do |robot|
execution_id = client.runs(robot.list_run_id).execute(connect: true)
end
end
我已在控制器中尝试了此代码。但它不起作用
Tasks::scriping.execute
当在控制台中运行此命令时,它会工作
bundle exec rake scriping:list
如何调用任务:list此任务来自controller最佳解决方案是将共享代码移动到类中
# app/services/cloud_scrape_client_runner.rb
class CloudScrapeClientRunner
def self.perform
client = CloudscrapeClient.new
Robot.all.each do |robot|
execution_id = client.runs(robot.list_run_id).execute(connect: true)
end
end
end
然后确保您正在加载该文件夹
# in config/application.rb:
config.autoload_paths << Rails.root.join('services')
在控制器中:
class FooController < ApplicationController
def index
CloudScrapeClientRunner.perform
end
end
class FooController
为什么
因为我猜CloudScrapeClientSomething
是slooow,您希望异步执行它
你想要什么:点击链接,让它触发控制器启动任务
你不想要的:单击链接,冻结整个应用程序,直到任务完成 最好的解决方案是将共享代码移动到类中
# app/services/cloud_scrape_client_runner.rb
class CloudScrapeClientRunner
def self.perform
client = CloudscrapeClient.new
Robot.all.each do |robot|
execution_id = client.runs(robot.list_run_id).execute(connect: true)
end
end
end
然后确保您正在加载该文件夹
# in config/application.rb:
config.autoload_paths << Rails.root.join('services')
在控制器中:
class FooController < ApplicationController
def index
CloudScrapeClientRunner.perform
end
end
class FooController
为什么
因为我猜CloudScrapeClientSomething
是slooow,您希望异步执行它
你想要什么:点击链接,让它触发控制器启动任务
你不想要的:单击链接,冻结整个应用程序,直到任务完成 谢谢你,但这对我来说是个错误。未初始化的常量AdminController::CloudScrapeClientRunner您应该为这些内容添加一个名为
libs
的额外文件夹。并将其添加到自动加载路径,谢谢你,但我认为这是一个错误。未初始化的常量AdminController::CloudScrapeClientRunner您应该为这些内容添加一个名为libs
的额外文件夹。并将其添加到自动加载路径