-
Notifications
You must be signed in to change notification settings - Fork 3
Clear Old Conversations in ActiveRecord with Clockwork and ActiveJob
We'll want to make sure that old conversations are removed from the database to conserve space. By that point, the user probably won't expect context to be saved.
I use squeel for SQL queries - but it's not required. My example won't work without it, but it's somewhat simple to replace it with a normal query.
Read clockwork's guide, and make sure you have a solution for running it in production (it doesn't run alongside your app, but instead in it's own process).
You should make sure that you have a good solution for running jobs in the background. I recommend GitHub's resque.
$ rails generate wit_bot:clear_conversations_job
First, let's create the job. It doesn't need a high priority in resque, so queue_as
should be :low
. All that the job needs to do is find all conversations not updated since last 4 hours ago, and destroy them all.
class ClearConversationsJob < ActiveJob::Base
queue_as :low
def perform
# Find all conversations not updated in the last 4 hours, and destroy them.
Conversation.where{ updated_at <= 4.hours.ago }.destroy_all
end
end
Now, you'll want to install the clockwork gem (unless you already have job scheduler, in which case, by all means, use that one). Add this to your Gemfile, and bundle
.
# For scheduled jobs
gem 'clockwork', '~> 1.2.0'
In the root of your project, create a clock.rb
file, and set it to run the ClearConversationsJob every hour:
require 'clockwork'
require_relative 'config/boot'
require_relative 'config/environment'
module Clockwork
every(1.hour, 'Clear Old Conversations') { ClearConversationsJob.perform_later }
end
And run it:
$ clockwork clock.rb
Yay! Old conversations will be cleared every hour!
Down here?
Cool.
I should add something somewhat interesting for you to read...
Here's how to get started with wit_bot in 3 steps:
- Learn how to use wit.ai
- Learn how to setup the gem
- Learn how to send a message
- Learn how to use message threads
- Learn how to use context
- Learn how to use conversations
- Learn to use the REPL
- Learn how to use conversations
- Learn how to use participants
- Learn how to use bots