Skip to content

Instantly share code, notes, and snippets.

@bobuss
Last active December 13, 2015 22:49
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 bobuss/4987023 to your computer and use it in GitHub Desktop.
Save bobuss/4987023 to your computer and use it in GitHub Desktop.
Stamina recovery mecanism inside Redis TTLs

A what you want point recovery system inside a TTL storage

Requirements

  • virtualenv
  • a Redis server up and running on your machine, default port (6379).

Test it

$ git clone https://gist.github.com/4987023.git
$ cd 4987023
$ virtualenv env
$ . env/bin/activate
$ pip install redis
$ ./env/bin/python player.py
Player bob just created
Player bob (stamina=100)

Let's decrease its stamina
Player bob (stamina=90)

And wait for 1 second
have a look to the stamina
Player bob (stamina=91)

and again, wait for 2 seconds

And now the stamina is
Player bob (stamina=93)

A stamina recovery mecanism inside redis TTL... fun :)
import redis
import time
conf = {
'host': 'localhost',
'port': 6379
}
pool = redis.ConnectionPool(host=conf['host'], port=conf['port'])
redis = redis.Redis(connection_pool=pool)
class Player(object):
MAX_STAMINA = 100
RECOVERY_TIME = 1
def __init__(self, name):
self.name = name
self.stamina = Player.MAX_STAMINA
def _get_redis_key(self):
return 'player:%s:stamina' % self.name
def get_stamina(self):
ttl = redis.ttl(self._get_redis_key())
return Player.MAX_STAMINA if ttl is None\
else int(Player.MAX_STAMINA - (float(ttl) / Player.RECOVERY_TIME))
def set_stamina(self, value):
key = self._get_redis_key()
with redis.pipeline(transaction=True) as pipe:
pipe.multi()
pipe.set(key, value)
ttl = int(Player.RECOVERY_TIME * (Player.MAX_STAMINA - value))
if ttl > 0:
pipe.expire(key, ttl)
pipe.execute()
return self
stamina = property(get_stamina, set_stamina)
def __repr__(self):
return 'Player %s (stamina=%d)' % (self.name, self.stamina)
if __name__ == '__main__':
player1 = Player('bob')
print 'Player bob just created'
print player1
# decrease the stamina
player1.stamina = Player.MAX_STAMINA - 10
print '\nLet\'s decrease its stamina'
print player1
print '\nAnd wait for 1 second'
time.sleep(1)
print 'have a look to the stamina'
print player1
print '\nand again, wait for 2 seconds'
time.sleep(2)
print '\nAnd now the stamina is'
print player1
print '\nA stamina recovery mecanism inside redis TTL... fun :)\n'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment