Class: Scheddy::TaskScheduler

Inherits:
ApplicationRecord show all
Defined in:
app/models/scheddy/task_scheduler.rb

Instance Method Summary collapse

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

Returns:

  • (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

Returns:

  • (Boolean)


21
22
23
# File 'app/models/scheddy/task_scheduler.rb', line 21

def leader?
  leader_state == 'leader'
end

#mark_seenObject



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_leadershipObject



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_stepdownObject



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_leadershipObject



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