简体   繁体   中英

how to call rake tasks from controller in rails

i have this task in /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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM