How do I use Rails clockwork gem to run rake tasks?

后端 未结 4 1422
半阙折子戏
半阙折子戏 2021-01-02 03:23

What is the syntax for calling rake tasks from clockwork? I\'ve tried all kinds of syntax, and nothing seems to work. (I\'m specifically interested in clockwork because Her

相关标签:
4条回答
  • 2021-01-02 03:57

    You can pass in a block to every that executes your rake task:

    every(1.day, "namespace:task") do
      ApplicationName::Application.load_tasks
      Rake::Task['namespace:task'].invoke
    end
    
    0 讨论(0)
  • 2021-01-02 04:05

    Invoking the task using Rake::Task['...'].invoke works well the first time, but the task need to be reenabled to be invoked again later.

        ApplicationName::Application.load_tasks
    
        module Clockwork do
            every(10.minutes, "namespace:task") do
              Rake::Task['namespace:task'].invoke
              Rake::Task['namespace:task'].reenable
            end
        end
    

    Otherwise the task will be invoked the first time, but no more after that until the clockwork process is restarted.

    0 讨论(0)
  • 2021-01-02 04:06

    rake is not a method, so you can't invoke it like that here.

    You can either shell out and invoke it, something like

    every(30.seconds, 'Send Messages') {
      `rake scheduler:send_messages`
    }
    

    or rather invoke a new detached process using the heroku API. This is my preferred method right now:

    Heroku::API.new.post_ps('your-app', 'rake scheduler:send_messages')
    

    Heroku::API is available from heroku.rb: https://github.com/heroku/heroku.rb

    0 讨论(0)
  • 2021-01-02 04:06

    You can add the following method to your clock.rb file:

    def execute_rake(file,task)
    require 'rake'
    rake = Rake::Application.new
    Rake.application = rake
    Rake::Task.define_task(:environment)
    load "#{Rails.root}/lib/tasks/#{file}"
    rake[task].invoke
    end
    

    and then call

    execute_rake("your_rake_file.rake","your:rake:task")
    

    in your handler

    0 讨论(0)
提交回复
热议问题