Skip to content

Instantly share code, notes, and snippets.

@nkwhr
Created October 10, 2014 07:30
Show Gist options
  • Save nkwhr/344b87ae9adb2b2830b9 to your computer and use it in GitHub Desktop.
Save nkwhr/344b87ae9adb2b2830b9 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use sane;
use Redis::Fast;
use Time::Piece;
use DDP;
my $user_id = 100;
my $u = UserLastAccess->new(user_id => $id);
p $u->touch;
p $u->last_accessed_at;
my $start = 1412923653;
my $end = 1412923656;
p $u->users_in_range($start, $end);
package UserLastAccess;
use constant {
KEY => 'user_last_access'
};
sub new {
my ($class, %args) = @_;
bless {
user_id => $args{user_id} || undef,
key => KEY,
redis => Redis::Fast->new(),
}, $class;
}
sub last_accessed_at {
my $self = shift;
my $timestamp = $self->{redis}->zscore($self->{key}, $self->{user_id});
if ($timestamp) {
return _unixtime_to_datetime($timestamp);
}
return undef;
}
sub touch {
my $self = shift;
my $timestamp = time();
$self->{redis}->zadd($self->{key}, $timestamp, $self->{user_id});
return _unixtime_to_datetime($timestamp);
}
sub users_in_range {
my $self = shift;
my ($start, $end) = @_;
my %users_with_timestamp = $self->{redis}->zrangebyscore(KEY, $start, $end, 'withscores');
return \%users_with_timestamp;
}
sub _unixtime_to_datetime {
my $unixtime = shift;
Time::Piece::localtime($unixtime)->strftime('%Y/%m/%d(%a) %H:%M');
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment