2

I have a database that contains some tweets/text that I want posted to twitter in a set interval (for example: every 60 seconds). The tweets should iterate through a for loop and post one tweet in every time interval.

I have written a method that does this for one tweet and then sleeps for 60 seconds.

class TweetsController < ApplicationController

    def create
        Tweet.all.each do |t|
            current_user.tweet(t.text)
            sleep 60
        end
      end
end

That basically does what I am trying to achieve but needs to be asynchronous and in the background. I have tried and succeeded installing redis/resque but failed to get the jobs implemented and working. I am new to rails and have never set up a background worker/job before.

I have a Sender.rb Job in resque implemented

class Sender
    def self.queue = :tweets_queue end

        def self.perform user_id
            Tweet.all.each do |t|
                current_user.tweet(t.text)
            end
        end

    end 

I have implemented resque according to the documentation and autoload all job folders automatically.

But I am currently running into several problems. Like this, the for loop runs every time I would start the worker (I have never get it to run). I need to figure out how the worker can iterate through the database entries one by one every time the job starts. Also how can I scheduled the job to be executed (Like for example run the Sender.rb job every 60 seconds or every 24h etc)? Sorry for the little vague post, but I have been trying to wrap my head around this for a couple of days and getting nowhere.

Jan
  • 239
  • 1
  • 4
  • 17

1 Answers1

0

You are looking for whenever gem. This gem provides a pretty easy syntax for writing and deploying cron jobs. You'll be able to write in schedule.rb file something like:

every 1.minute do
  runner "Sender.enqueue" 
end

You can set and then get your tweet number in Redis and after publishing tweet increment it by 1, like:

offset = redis.get('offset')
Tweet.offset(offset - 1).first
Ilya
  • 13,337
  • 5
  • 37
  • 53