user1938700
user1938700

Reputation: 39

Run Method Certain Time, Day, Year (Ruby)

I am writing a ruby program that will ask a user a to type a message, then a year, month, day and time and then email a message when that time comes. I store that data into a database table. The program should loop until that day comes and then carry out the sending.

Without using a database, I have written the following:

def send_Message(m_to, m_from, m_body, month, day, year, hour, min)
x = 0
t = Time.now


if (t.day == day 
    && t.month == month 
    && t.year == year 
    && t.strftime("%I") == hour 
    && t.strftime("%M") == min )

    x = x +5

    message = @client.account.sms.messages.create(:body => m_body,
        :to => m_to,
        :from => m_from)
    puts message.sid   

else
    sleep_time = Time.new(year,month,day)
    total_sleep = sleep_time - t
    sleep(total_sleep)
    message = @client.account.sms.messages.create(:body => m_body,
        :to => m_to,
        :from => m_from)
    puts message.sid  
end

end

but it only really seems to work with the month, day, year thing, but not time. There are two questions I am seeking an answer to: how can I carry out looping through a database, seeking chronologically messages to send, and with my example code above, how can I use the hour and minute of the day along with the day month and year to send the message.

P.S: I am designing this app on over to rails, where a user/app sends an API request and then the process I mentioned will be carried out.

Upvotes: 0

Views: 2125

Answers (1)

drhenner
drhenner

Reputation: 2230

You have a few approaches: Look into the gem whenever

 gem install whenever

https://github.com/javan/whenever

It doesn't do exactly what you asked but it is much better than running ruby for 6 month's waiting for an email to be sent.

An even better approach is resque https://github.com/defunkt/resque

Then add https://github.com/bvandenbos/resque-scheduler and your solution is very nice without the drag of a million ruby instances waiting to send an email.

Good Luck...

BTW: I made a service to do exactly what you are asking. I have specs and the code. If you want I can get it to you.

Upvotes: 2

Related Questions