简体   繁体   中英

Can I use Whenever Gem with a Module Method in Rails

I've created a very small application in rails where I've created a module method in /lib to handle the logic.

I've also set up Whenever to run that Module Method at set times. I've followed both the readme from Whenever and these previous posts to hopefully set things up correctly.

When looking at the readme though the examples are quoted like this:

every 3.hours do
  runner "MyModel.some_process"
  rake "my:rake:task"
  command "/usr/bin/my_great_command"
end

every 1.day, :at => '4:30 am' do
  runner "MyModel.task_to_run_at_four_thirty_in_the_morning"
end

every :hour do # Many shortcuts available: :hour, :day, :month, :year, :reboot
  runner "SomeModel.ladeeda"
end

My question therefore is does whenever have to reference a method in the model? or can it reference a module method in /lib? Looking at this post it seems to allude to having to have the method in the model.

My problem is that I don't have a database and so no models.

Any help would be appreciated.

It can reference a method in any class or or any module. (A module is just a class that can't instantiate).

If there's some intermediate data that you need to pass between methods in your module, it sometimes helps to make the module a PORO (plain old Ruby object) class, which lets you instantiate (ie use the new and initialize methods) and you can store values in attr_accessor attributes available to all instance methods for that object.

You don't have to call methods on models only. As far as a class/module is available/accessible in your current scope, you can call it. Since runner can access models, probably you have setup the whenever gem to load rails app as well. It means that it can also access any classes/modules in your /lib folder as well.

So, go ahead and call then in your whenever:

every 3.hours do
  runner "YourModule.some_method"
end

If you are not using any Rails specific features, I would suggest not to load Rails env. You would save significant resources and it will perform faster.

Alternatively, create a rake task that does the processing and invoke that instead. As a benefit, you would end up with a rake task you can call and test yourself.

every 3.hours do
  rake "cron:my_process"
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM