Skip to content

Commit

Permalink
Do mysql lock within a transaction
Browse files Browse the repository at this point in the history
  • Loading branch information
albus522 committed Nov 8, 2019
1 parent 5aaba39 commit 29a9025
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions lib/delayed/backend/active_record.rb
Original file line number Diff line number Diff line change
Expand Up @@ -147,13 +147,16 @@ def self.reserve_with_scope_using_optimized_mysql(ready_scope, worker, now)
# while updating. But during the where clause, for mysql(>=5.6.4),
# it queries with precision as well. So removing the precision
now = now.change(usec: 0)

# This works on MySQL and possibly some other DBs that support
# UPDATE...LIMIT. It uses separate queries to lock and return the job
sets = "locked_at = :now, locked_by = :name, id = (SELECT @dj_update_id := id)"
count = ready_scope.limit(1).update_all([sets, now: now, name: worker.name])
return nil if count == 0
transaction do
count = ready_scope.limit(1).update_all([sets, now: now, name: worker.name])
return nil if count == 0

find_by("id = @dj_update_id")
where("id = @dj_update_id").first
end
end

def self.reserve_with_scope_using_optimized_mssql(ready_scope, worker, now)
Expand Down

0 comments on commit 29a9025

Please sign in to comment.