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

Use a transaction when enqueuing a job to ensure atomicity #223

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
52 changes: 37 additions & 15 deletions rq_scheduler/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,23 +365,45 @@ def enqueue_job(self, job):
job.meta['repeat'] = int(repeat) - 1

queue = self.get_queue_for_job(job)
queue.enqueue_job(job)
self.connection.zrem(self.scheduled_jobs_key, job.id)

if interval:
# If this is a repeat job and counter has reached 0, don't repeat
if repeat is not None:
if job.meta['repeat'] == 0:
return
self.connection.zadd(self.scheduled_jobs_key,
{job.id: to_unix(datetime.utcnow()) + int(interval)})
elif cron_string:
# If this is a repeat job and counter has reached 0, don't repeat
if repeat is not None:
if job.meta['repeat'] == 0:
with self.connection.pipeline() as pipe:
while True:
try:
pipe.watch(self.scheduled_jobs_key)
queue.enqueue_job(job)
pipe.multi()
pipe.zrem(self.scheduled_jobs_key, job.id)

if not (interval or cron_string):
pipe.execute()
return

# If this is a repeat job and counter has reached 0, don't repeat
if repeat is not None:
if job.meta['repeat'] == 0:
pipe.execute()
return

next_scheduled_time = (
Copy link
Contributor

Choose a reason for hiding this comment

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

Could you explain the rationale behind changing the way which next_scheduled_time calculation is different than the current implementation?

to_unix(datetime.utcnow()) + int(interval)
if interval else
to_unix(
get_next_scheduled_time(
cron_string,
use_local_timezone=use_local_timezone
)
)
)

pipe.zadd(self.scheduled_jobs_key, {job.id: next_scheduled_time})
pipe.execute()
return
self.connection.zadd(self.scheduled_jobs_key,
{job.id: to_unix(get_next_scheduled_time(cron_string, use_local_timezone=use_local_timezone))})
except WatchError:
self.log.info(
"{} changed between the time of watching "
"and the pipeline's execution.".format(self.scheduled_jobs_key)
)
continue

def enqueue_jobs(self):
"""
Expand Down