Class: Scheddy::TaskScheduler
- Inherits:
-
ApplicationRecord
- Object
- ActiveRecord::Base
- ApplicationRecord
- Scheddy::TaskScheduler
- Defined in:
- app/models/scheddy/task_scheduler.rb
Instance Method Summary collapse
- #clear_leader(only_if_expired: false) ⇒ Object
- #expired? ⇒ Boolean
- #leader? ⇒ Boolean
- #mark_seen ⇒ Object
- #renew_leadership ⇒ Object
- #request_stepdown ⇒ Object
- #take_leadership ⇒ Object
Instance Method Details
#clear_leader(only_if_expired: false) ⇒ Object
26 27 28 29 30 31 32 33 |
# File 'app/models/scheddy/task_scheduler.rb', line 26 def clear_leader(only_if_expired: false) reload if changed? with_lock do if !only_if_expired || expired? update! leader_state: nil, leader_expires_at: nil end end end |
#expired? ⇒ Boolean
17 18 19 |
# File 'app/models/scheddy/task_scheduler.rb', line 17 def expired? leader_expires_at && leader_expires_at < Time.current end |
#leader? ⇒ Boolean
21 22 23 |
# File 'app/models/scheddy/task_scheduler.rb', line 21 def leader? leader_state == 'leader' end |
#mark_seen ⇒ Object
35 36 37 38 39 |
# File 'app/models/scheddy/task_scheduler.rb', line 35 def mark_seen if last_seen_at < (LEASE_RENEWAL_INTERVAL - 5.seconds).ago update! last_seen_at: Time.current end end |
#renew_leadership ⇒ Object
41 42 43 44 45 46 47 48 49 50 |
# File 'app/models/scheddy/task_scheduler.rb', line 41 def renew_leadership if last_seen_at < (LEASE_RENEWAL_INTERVAL - 5.seconds).ago update! leader_expires_at: LEASE_DURATION.from_now, last_seen_at: Time.current else true end rescue ActiveRecord::StaleObjectError reload false end |
#request_stepdown ⇒ Object
58 59 60 61 |
# File 'app/models/scheddy/task_scheduler.rb', line 58 def request_stepdown # intentionally leaves self.lock_version behind self.class.increment_counter :lock_version, id, touch: true if leader? end |
#take_leadership ⇒ Object
52 53 54 55 56 |
# File 'app/models/scheddy/task_scheduler.rb', line 52 def take_leadership update! leader_state: 'leader', leader_expires_at: LEASE_DURATION.from_now, last_seen_at: Time.current rescue ActiveRecord::RecordNotUnique false end |