[英]How can I run a “cron script” on heroku by user interaction on Rails?
I have the following script which runs once a day on cron on heroku. 我有以下脚本,该脚本每天在heroku的cron上运行一次。
However, I realize that I would like the option for the user to be able to press a button from a web page to initiate this same process. 但是,我意识到,我希望用户能够通过按下网页上的按钮来启动此过程。
Is there a way to create a 'subroutine' that either cron can call or from a web request? 有没有一种方法可以创建cron可以调用或从Web请求调用的“子例程”? I don't want to use a separate service that runs jobs.
我不想使用运行作业的单独服务。
I've just put a snippet to illustrate..... 我只是添加了一个片段来说明.....
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")
I've done this by putting the function in question in a file in lib (lib/tasks_n_stuff.rb, say): 我通过将有问题的函数放在lib(例如lib / tasks_n_stuff.rb)的文件中来完成此操作:
module TasksNStuff
def self.do_something
# ...doing something...
end
end
Then I can call if from a Rake task: 然后我可以打电话给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
Or from a controller (or anywhere, really): 或从控制器(或任何地方,实际上):
class WhateverController < ApplicationController
def do_something
TasksNStuff.do_something
end
end
And since you can run a rake task as a cron job ( cd /my/rails/root; rake do_something
), that should be all you need. 并且由于您可以将rake任务作为cron作业运行(
cd /my/rails/root; rake do_something
),所以这应该是您所需要的。 Cheers! 干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.