0

I am writing a ruby scheduler - namely rufus-scheduler and there are commands i need to write in the initializers section inside the config folder to perform a task every 1 minute or so. I am trying to access a method from a module within this. So my code would look like

scheduler.every("1m") do
  puts("HELLO #{Time.now}")
  ModelName.methodname("WHAT ARE YOU DOING")
end

This somehow doesn't perform the necessary operation in the model. Also im not sure if this is the right way to do things - such as call a model inside a config file. Is there a better place to put this code in the Model? Or is calling a Model within config files perfectly good practice. I looked over the internet to see the usage of different types of files in ruby but couldn't find a proper material. Any help or guidance appreciated.

Taryn East
  • 27,486
  • 9
  • 86
  • 108
CodeGeek123
  • 4,341
  • 8
  • 50
  • 79

2 Answers2

2

If you want to access models from stand-alone tasks the best way is to use the rails runner wrapper. For example, you'd call your script as:

rails runner call_model.rb

This loads in the Rails environment and then executes your script, eliminating the need to do that yourself. Models on their own will not work since they are lacking the context of Rails.

If that's not sufficient, you may need to load the Rails environment more directly by including config/environment.rb into your rufus-scheduler configuration.

tadman
  • 208,517
  • 23
  • 234
  • 262
1

It sounds like you actually want a real scheduled action of some sort. config files are for configuration, not for actual working code of that sort.

There are tons of ways to run scheduled tasks in rails.

google "rails daemons" or "rails scheduled tasks" to start you off.

Here's a good list of scheduled-task best practices using cron: A cron job for rails: best practices?

Community
  • 1
  • 1
Taryn East
  • 27,486
  • 9
  • 86
  • 108