@@ -102,51 +102,47 @@ final class Monitor:@unchecked Sendable{
102
102
final class Pinging : @unchecked Sendable {
103
103
private let queue : DispatchQueue = . init( label: " mqtt.ping.queue " )
104
104
private let config : Config
105
- private var tryCount : UInt8 = 0
106
- private var lastTime : DispatchTime
107
- private var item : DispatchWorkItem ?
105
+ private var execTime : DispatchTime
106
+ private var worker : DispatchWorkItem ?
108
107
private weak var client : MQTTClient ?
109
108
init ( client: MQTTClient ) {
110
- lastTime = . now( )
109
+ execTime = . now( )
111
110
config = client. config
112
111
self . client = client
113
112
}
114
113
func start( ) {
115
114
guard config. pingEnabled else { return }
116
- guard item == nil else { return }
117
- tryCount = 0
118
- lastTime = . now( )
115
+ guard worker == nil else { return }
116
+ execTime = . now( )
119
117
schedule ( )
120
118
}
121
119
func cancel( ) {
122
- if item != nil {
123
- item? . cancel ( )
124
- item = nil
120
+ queue. async {
121
+ if self . worker != nil {
122
+ self . worker? . cancel ( )
123
+ self . worker = nil
124
+ }
125
125
}
126
126
}
127
127
func update( ) {
128
- lastTime = . now( )
128
+ self . execTime = . now( )
129
129
}
130
130
private func schedule( ) {
131
- let item = DispatchWorkItem { [ weak self] in
131
+ let worker = DispatchWorkItem { [ weak self] in
132
132
guard let self else { return }
133
133
guard let client = self . client else { return }
134
- if self . lastTime+ TimeInterval( self . config. keepAlive) <= . now( ) {
135
- client. ping ( ) . finally { result in
136
- if case . failure = result{
137
- self . tryCount += 1
138
- if self . tryCount >= self . config. maxPingCount{
139
- client. pingTimeout ( )
140
- }
141
- }
142
- self . update ( )
143
- self . schedule ( )
144
- }
145
- } else {
134
+ guard self . execTime+ TimeInterval( self . config. keepAlive) <= . now( ) else {
146
135
self . schedule ( )
136
+ return
137
+ }
138
+ client. ping ( ) . finally { result in
139
+ if case . failure = result{
140
+ client. pingTimeout ( )
141
+ }
147
142
}
143
+ self . schedule ( )
148
144
}
149
- queue. asyncAfter ( deadline: lastTime + TimeInterval( config. keepAlive) , execute: item )
150
- self . item = item
145
+ self . queue. asyncAfter ( deadline: execTime + TimeInterval( config. keepAlive) , execute: worker )
146
+ self . worker = worker
151
147
}
152
148
}
0 commit comments