Skip to content

Commit

Permalink
schedule: Add the 'count' argument.
Browse files Browse the repository at this point in the history
  • Loading branch information
progval committed Aug 4, 2013
1 parent 61e5ede commit 6a47500
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/schedule.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@

import time
import heapq
import functools
from threading import Lock

import supybot.log as log
Expand Down Expand Up @@ -109,14 +110,19 @@ def rescheduleEvent(self, name, t):
f = self.removeEvent(name)
self.addEvent(f, t, name=name)

def addPeriodicEvent(self, f, t, name=None, now=True, args=[], kwargs={}):
def addPeriodicEvent(self, f, t, name=None, now=True, args=[], kwargs={},
count=None):
"""Adds a periodic event that is called every t seconds."""
def wrapper():
def wrapper(count):
try:
f(*args, **kwargs)
finally:
# Even if it raises an exception, let's schedule it.
return self.addEvent(wrapper, time.time() + t, name)
if count[0] is not None:
count[0] -= 1
if count[0] is None or count[0] > 0:
return self.addEvent(wrapper, time.time() + t, name)
wrapper = functools.partial(wrapper, [count])
if now:
return wrapper()
else:
Expand Down
22 changes: 22 additions & 0 deletions test/test_schedule.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,28 @@ def inc():
sched.run() # 3.4
self.assertEqual(i[0], 3)

def testCountedPeriodic(self):
sched = schedule.Schedule()
i = [0]
def inc():
i[0] += 1
n = sched.addPeriodicEvent(inc, 1, name='test_periodic', count=3)
time.sleep(0.6)
sched.run() # 0.6
self.assertEqual(i[0], 1)
time.sleep(0.6)
sched.run() # 1.2
self.assertEqual(i[0], 2)
time.sleep(0.6)
sched.run() # 1.8
self.assertEqual(i[0], 2)
time.sleep(0.6)
sched.run() # 2.4
self.assertEqual(i[0], 3)
time.sleep(1)
sched.run() # 3.4
self.assertEqual(i[0], 3)


# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:

0 comments on commit 6a47500

Please sign in to comment.