[英]how to call rake tasks from controller in rails
i have this task in /lib/tasks/scriping.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)
end
end
i have tried this code in controller. 我已经在控制器中尝试过此代码。 But it's not working.
但这不起作用。
Tasks::scriping.execute
When is run this command in console it works! 当在控制台中运行此命令时,它将起作用!
bundle exec rake scriping:list
how can i call task :list this task from controller 我该如何调用任务:从控制器中列出此任务
Best solution is to move that shared code to a class! 最好的解决方案是将共享代码移到类中!
# 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
Then make sure you're loading that folder 然后确保您正在加载该文件夹
# in config/application.rb:
config.autoload_paths << Rails.root.join('services')
Then in your rake task: 然后在您的耙任务中:
namespace :scriping do
task :list => :environment do
CloudScrapeClientRunner.perform
end
end
and in your controller: 并在您的控制器中:
class FooController < ApplicationController
def index
CloudScrapeClientRunner.perform
end
end
WHY!?! 为什么!?!
Because I am guessing that CloudScrapeClientSomething
is sloooow and you want to do it asynchronously. 因为我猜想
CloudScrapeClientSomething
是sloooow,而您想异步进行。
what you want: click link, have it trigger the controller to start the task. 您想要的是:单击链接,使其触发控制器以启动任务。
what you don't want: click the link, have the entire app freeze until the task is completed. 您不需要的功能:单击链接,冻结整个应用程序,直到任务完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.