Skip to content

Instantly share code, notes, and snippets.

@basicfeatures
Last active January 18, 2022 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save basicfeatures/1c649a5336bfaf2c8c54ee01b72648f9 to your computer and use it in GitHub Desktop.
Save basicfeatures/1c649a5336bfaf2c8c54ee01b72648f9 to your computer and use it in GitHub Desktop.

MyBlog

rails new myblog
rails generate scaffold Post title:string body:text && rails db:migrate
rails generate migration AddPublishedFlagToPosts published:boolean && rails db:migrate
rails generate job publish_posts_job

posts_controller.rb

def index
  @posts = Post.where(published: true)
end

publish_posts_job.rb

class PublishPostsJob < ApplicationJob
  queue_as :default

  after_perform :repeat

  def perform
    # Find an unpublished post
    @post = Post.where(published: false).sample

    # Publish it
    @post.update(published: true)
  end

  private
    def repeat
      self.class.set(wait: 5.hours).perform_later
    end
end

Start the first job

% rails console
irb(main):001:0> PublishPostsJob.perform_now
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment