1

I have the following class method I call through the Whatever gem. If I call the method from the Rails console it works perfectly. If it is called from the Whatever cron job, the first two logger calls show up in the log file, so I know it is being called okay. However, the third one does not.

It seems that executing the method as a cron job recognizes the class, but is not connected to the database to retrieve individual instances of "Message"

Any help is appreciated

def self.check_saved_messages

    #Code to test the method with the 'whenever' gem.   
    my_logger.warn("Scheduler fired at #{Time.now} Logger 1") 

    # 1. Grab all messages that have not been sent.
    @messages = Array.new #Creates new array to store messages in.

    #Stores all messages that have not been sent in @messages array.
    my_logger.warn("Scheduler fired at #{Time.now} #{Message.all} Logger 2") #Works as Cron job
    my_logger.warn("Scheduler fired at #{Time.now} #{Message.last} Logger 3") #Doesn't work as cron job

    Message.where(sent: false).find_each do |message|
              @messages.push(message)
    end

    # 2. Iterate through them and find the ones where the time has past to send.
    current_time = Time.now.utc

    #Send messages that have a send_time earlier than current time.
    @messages.each do |message|
        if  current_time.to_i > message.send_time.to_i
            message.send_message 
            message.send_time # Testing (working)
        end
    end

end
7urkm3n
  • 6,054
  • 4
  • 29
  • 46
wibberding
  • 815
  • 3
  • 10
  • 17

2 Answers2

1

When I start the 'whenever' command with the development environment, so it can actually connect to the development database, it works perfectly :-)

whenever --update-crontab --set environment='development'

wibberding
  • 815
  • 3
  • 10
  • 17
0

By default the whatever gem will run in a production environment. As your likely to first test it in a development environment this will cause an issue as it will try to connect to your production database which won't exist.

You can solve these two ways:

explicitly set the environment on method invocation

runner "Model.some_method", :environment => 'development'

or set it when updating the crontab

whenever --update-crontab --set environment='development'
Gino
  • 1,043
  • 16
  • 27