0

just registered so I could ask this question.

Right now I have this code that prevents a class from updating more than once every five minutes:

now = datetime.now()
delta = now - myClass.last_updated_date
seconds = delta.seconds

if seconds > 300
    update(myClass)     
else
    retrieveFromCache(myClass)

I'd like to modify it by allowing myClass to update twice per 5 minutes, instead of just once.

I was thinking of creating a list to store the last two times myClass was updated, and comparing against those in the if statement, but I fear my code will get convoluted and harder to read if I go that route.

Is there a simpler way to do this?

3
  • Is this part of a larger project? Commented Jan 30, 2013 at 23:55
  • it is, I generalized the small piece I'm working on right now Commented Jan 30, 2013 at 23:56
  • 1
    Count how many times you've updated since seconds and incorporate that in your logic. Commented Jan 30, 2013 at 23:57

1 Answer 1

1

You could do it with a simple counter. Concept is get_update_count tracks how often the class is updated.

if seconds > 300 or get_update_count(myClass) < 2:
    #and update updatecount
    update(myClass)     
else:
    #reset update count
    retrieveFromCache(myClass)

Im not sure how you uniquely identify myClass.

update_map = {}

def update(instance):
     #do the update
     update_map[instance] = update_map.get(instance,0)+1

def get_update_count(instance):
     return update_map[instance] or 0
Sign up to request clarification or add additional context in comments.

1 Comment

Ah yep that is so much cleaner. Thanks so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.