Skip to content

Instantly share code, notes, and snippets.

@jfernandez
Created November 29, 2010 21:11
Show Gist options
  • Save jfernandez/720630 to your computer and use it in GitHub Desktop.
Save jfernandez/720630 to your computer and use it in GitHub Desktop.
Active users in the last 5 minutes
# Inside the controller code that fetches the logged in user for every request
# Note: Trying to call EXPIRE against a key that already has an associated timeout will not change the timeout of the key, but will just return 0
redis = Redis.new
minutes = 5
seconds = minutes * 60
redis.multi do
redis.sadd("active-users", user.id)
redis.expire("active-users", seconds)
end
# To find current active users
User.find(redis.smembers("active-users"))
@jfernandez
Copy link
Author

This only works in Redis 2.1.3 or greater. If you're running an earlier version you will have to delete the 'active-users' key on a cron job or scheduled job.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment