Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 Heroku's supporting it.)

Here's my clock.rb, using the same syntax that the whenever gem uses:

module Clockwork
  puts "testing clockwork!"
  every(30.seconds, 'Send Messages') {
    rake 'scheduler:send_messages'
    }
end

And here's my rake task in scheduler.rake:

task :send_messages => :environment do
  puts "rake task run successfully!"
end

And here's what happens when I start a clockwork process:

$ clockwork lib/clock.rb
testing clockwork!
I, [2012-07-16T14:42:58.107245 #46427]  INFO -- : Starting clock for 1 events: [ Send Messages ]
I, [2012-07-16T14:42:58.107364 #46427]  INFO -- : Triggering 'Send Messages'
attempting to run rake task!
E, [2012-07-16T14:42:58.107437 #46427] ERROR -- : undefined method `rake' for Clockwork:Module (NoMethodError)

This runs every 30 seconds. As you can see, the clock.rb is executed successfully. But I can't for the life of me figure out the syntax to run a rake task. The clockwork readme is no help, unfortunately:

https://github.com/tomykaira/clockwork

like image 779
user1377556 Avatar asked Jul 16 '12 21:07

user1377556


1 Answers

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.

like image 181
Aurélien Reeves Avatar answered Sep 28 '22 04:09

Aurélien Reeves