我有以下脚本,每天在heroku上的cron上运行一次。
但是,我意识到我希望用户可以选择从网页上按下按钮来启动相同的过程。
有没有办法创建一个cron可以调用或来自Web请求的“子例程”?我不想使用运行作业的单独服务。
我只是用一个片段来说明......
letter_todos = Todo.current_date_lte(Date.today).asset_is("Letter").done_date_null
unless letter_todos.blank? #check if there any ToDos
# group by asset_id so that each batch is specific to the asset_id
letter_todos.group_by(&:asset_id).each do |asset_id, letter_todos|
# pdf = Prawn::Document.new(:margin => 100) #format the PDF document
html_file = ''
letter_todos.each do |todo| #loop through all Letter_Todos
contact = Contact.find(todo.contact_id) #get associated contact
letter = Letter.find(todo.asset_id) #get associated Letter
redcloth_contact_letter = RedCloth.new(letter.substituted_message(contact, [])).to_html
html_file = html_file + redcloth_contact_letter
html_file = html_file + "<p style='display: none; page-break-after: always'><center> ... </center> </p>"
end
kit = PDFKit.new(html_file)
kit.stylesheets << "#{RAILS_ROOT}/public/stylesheets/compiled/pdf.css"
file = kit.to_pdf
letter = Letter.find(asset_id)
#OutboundMailer.deliver_pdf_email(file)
kit.to_file("#{RAILS_ROOT}/tmp/PDF-#{letter.title}-#{Date.today}.pdf")
# Create new BatchPrint record
batch = BatchPrint.new
batch.pdf = File.new("#{RAILS_ROOT}/tmp/PDF-#{letter.title}-#{Date.today}.pdf")
答案 0 :(得分:0)
我是通过将相关函数放在lib(lib / tasks_n_stuff.rb,比如说)中的文件中完成的:
module TasksNStuff
def self.do_something
# ...doing something...
end
end
然后我可以通过Rake任务调用:
desc 'Make sure we depend on :environment, so we can get to the Railsy stuff...'
task :do_something => :environment do
TasksNStuff.do_something
end
或者从控制器(或任何地方,真的):
class WhateverController < ApplicationController
def do_something
TasksNStuff.do_something
end
end
由于您可以将rake任务作为cron作业运行(cd /my/rails/root; rake do_something
),这应该就是您所需要的。干杯!