Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow using scheduler as a context manager #154

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions rq_scheduler/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,18 @@ def __init__(self, queue_name='default', interval=60, connection=None):
self.log = logger
self._lock_acquired = False

def __enter__(self):
while True:
try:
self.register_birth()
return self
except ValueError: # assume register_birth failed
self.log.info('Waiting for registering birth...')
time.sleep(self._interval)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should let this exception be raised and let the user handle it. I'm not comfortable with implicitly calling sleep() which will block code execution.


def __exit__(self, exc_type, exc_val, exc_tb):
self.register_death()

def register_birth(self):
if self.connection.exists(self.scheduler_key) and \
not self.connection.hexists(self.scheduler_key, 'death'):
Expand Down Expand Up @@ -364,7 +376,6 @@ def run(self, burst=False):
"""
self.log.info('Running RQ scheduler...')

self.register_birth()
self._install_signal_handlers()

try:
Expand All @@ -384,4 +395,3 @@ def run(self, burst=False):
time.sleep(self._interval - (time.time() - start_time))
finally:
self.remove_lock()
self.register_death()
4 changes: 2 additions & 2 deletions rq_scheduler/scripts/rqscheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ def main():
level = 'INFO'
setup_loghandlers(level)

scheduler = Scheduler(connection=connection, interval=args.interval)
scheduler.run(burst=args.burst)
with Scheduler(connection=connection, interval=args.interval) as scheduler:
scheduler.run(burst=args.burst)

if __name__ == '__main__':
main()