问题
How do I create a delayed job from a rake file. How should I move it into a controller and create a delayed_job that runs the task every 15 minutes.
Here is an example how my rake file:
namespace :reklamer do
task :runall => [:iqmedier, :euroads, :mikkelsen] do
# This will run after all those tasks have run
end
task :iqmedier => :environment do
require 'Mechanize'
agent = WWW::Mechanize.new
agent.get("http://www.iqmedier.dk")
end
task :euroads => :environment do
require 'Mechanize'
require 'pp'
agent = Mechanize.new { |agent|
end
task :mikkelsen => :environment do
require 'Mechanize'
agent = Mechanize.new
agent.get("http://affilate.mikkelsenmedia.dk/partnersystem/mylogins.php")
end
end
What should I change to be a delayed job (https://github.com/collectiveidea/delayed_job)?
回答1:
Suggest you take a look at SimpleWorker, a cloud-based background processing / worker queue for Ruby apps. It's designed for offloading tasks, running scheduled jobs, and scaling out to handle many parallel jobs at once. It's simple, affordable, and scalable.
(Disclosure, I work for the company.)
You create your workers (in app/worker) and then in your controllers and elsewhere queue them up to run right away or schedule them for later or on a recurring basis with just a few lines of code. Here's a basic example.
worker = ReportWorker.new worker.user_id = @current_user.id worker.schedule(:start_at => 1.hours.since, :run_every => 900) #Or to run once right away #worker.queue
The ReportWorker class would contain the logic to create the report for the current user and sent it or post it needed.
回答2:
DelayedJob alone will not help you since it is based around one-time jobs. You will still need something that runs on a regular basis that creates these jobs.
Assuming:
- you're on Heroku and can only get a 1-hour cron
- you need to run a job every 15 minutes
You can do something like this...
Make a class for your jobs:
class MechanizeJob < Struct.new(:url)
def perform
agent = Mechanize.new
agent.get(url)
end
end
Schedule the jobs from your Rakefile:
task :schedulejobs => :environment do
urls = ["http://...", "http://...", "http://..."]
urls.each do |url|
# 1 is the job priority
Delayed::Job.enqueue MechanizeJob.new(url), 1, Time.now
Delayed::Job.enqueue MechanizeJob.new(url), 1, 15.minutes.from_now
Delayed::Job.enqueue MechanizeJob.new(url), 1, 30.minutes.from_now
Delayed::Job.enqueue MechanizeJob.new(url), 1, 45.minutes.from_now
end
end
This will run a job per url every 15 minutes.
来源:https://stackoverflow.com/questions/5661998/rails-help-creating-a-delayed-job-from-a-rake-file