2019-04-23 18:20:44 +02:00
|
|
|
//
|
|
|
|
// RefreshTimer.swift
|
|
|
|
// NetNewsWire
|
|
|
|
//
|
|
|
|
// Created by Maurice Parker on 4/23/19.
|
|
|
|
// Copyright © 2019 Ranchero Software. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
2019-05-16 00:21:58 +02:00
|
|
|
import Account
|
2019-04-23 18:20:44 +02:00
|
|
|
|
2024-03-20 07:05:30 +01:00
|
|
|
@MainActor final class AccountRefreshTimer {
|
2019-04-23 18:20:44 +02:00
|
|
|
|
|
|
|
var shuttingDown = false
|
2019-05-16 00:21:58 +02:00
|
|
|
|
2019-04-23 18:20:44 +02:00
|
|
|
private var internalTimer: Timer?
|
|
|
|
private var lastTimedRefresh: Date?
|
|
|
|
private let launchTime = Date()
|
|
|
|
|
|
|
|
func fireOldTimer() {
|
|
|
|
if let timer = internalTimer {
|
|
|
|
if timer.fireDate < Date() {
|
2020-07-02 03:57:36 +02:00
|
|
|
if AppDefaults.shared.refreshInterval != .manually {
|
2019-04-23 18:20:44 +02:00
|
|
|
timedRefresh(nil)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func invalidate() {
|
|
|
|
guard let timer = internalTimer else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if timer.isValid {
|
|
|
|
timer.invalidate()
|
|
|
|
}
|
|
|
|
internalTimer = nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func update() {
|
|
|
|
guard !shuttingDown else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-07-02 03:57:36 +02:00
|
|
|
let refreshInterval = AppDefaults.shared.refreshInterval
|
2019-04-23 18:20:44 +02:00
|
|
|
if refreshInterval == .manually {
|
|
|
|
invalidate()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
let lastRefreshDate = lastTimedRefresh ?? launchTime
|
|
|
|
let secondsToAdd = refreshInterval.inSeconds()
|
|
|
|
var nextRefreshTime = lastRefreshDate.addingTimeInterval(secondsToAdd)
|
|
|
|
if nextRefreshTime < Date() {
|
|
|
|
nextRefreshTime = Date().addingTimeInterval(secondsToAdd)
|
|
|
|
}
|
|
|
|
if let currentNextFireDate = internalTimer?.fireDate, currentNextFireDate == nextRefreshTime {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
invalidate()
|
|
|
|
let timer = Timer(fireAt: nextRefreshTime, interval: 0, target: self, selector: #selector(timedRefresh(_:)), userInfo: nil, repeats: false)
|
|
|
|
RunLoop.main.add(timer, forMode: .common)
|
|
|
|
internalTimer = timer
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2024-03-20 07:05:30 +01:00
|
|
|
@objc @MainActor func timedRefresh(_ sender: Timer?) {
|
2019-05-16 00:21:58 +02:00
|
|
|
|
2019-04-23 18:20:44 +02:00
|
|
|
guard !shuttingDown else {
|
|
|
|
return
|
|
|
|
}
|
2019-05-16 00:21:58 +02:00
|
|
|
|
2019-04-23 18:20:44 +02:00
|
|
|
lastTimedRefresh = Date()
|
|
|
|
update()
|
2019-05-16 00:21:58 +02:00
|
|
|
|
2024-03-26 07:36:27 +01:00
|
|
|
Task { @MainActor in
|
|
|
|
await AccountManager.shared.refreshAll()
|
|
|
|
}
|
2019-04-23 18:20:44 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|