@@ -3,8 +3,7 @@ use crate::matrix::MatrixClient;
3
3
use crate :: webhook:: Alert ;
4
4
use crate :: { unix_time, AlertId , Result } ;
5
5
use actix:: prelude:: * ;
6
- use std:: sync:: Arc ;
7
- use std:: sync:: atomic:: { AtomicBool , Ordering } ;
6
+ use std:: sync:: { Arc , Mutex } ;
8
7
use std:: time:: Duration ;
9
8
10
9
const CRON_JOB_INTERVAL : u64 = 5 ;
@@ -105,8 +104,7 @@ pub struct Processor {
105
104
escalation_window : u64 ,
106
105
should_escalate : bool ,
107
106
// Ensures that only one escalation task is running at the time.
108
- // `true` if locked, `false` if not.
109
- escalation_lock : Arc < AtomicBool > ,
107
+ escalation_lock : Arc < Mutex < ( ) > > ,
110
108
}
111
109
112
110
impl Processor {
@@ -115,7 +113,7 @@ impl Processor {
115
113
db : db. map ( |db| Arc :: new ( db) ) ,
116
114
escalation_window : escalation_window,
117
115
should_escalate : should_escalate,
118
- escalation_lock : Arc :: new ( AtomicBool :: new ( false ) ) ,
116
+ escalation_lock : Default :: default ( ) ,
119
117
}
120
118
}
121
119
fn db ( & self ) -> Arc < Database > {
@@ -168,26 +166,23 @@ impl Actor for Processor {
168
166
ctx. run_interval (
169
167
Duration :: from_secs ( CRON_JOB_INTERVAL ) ,
170
168
move |_proc, _ctx| {
171
- let is_locked = lock. load ( Ordering :: Relaxed ) ;
169
+ // Acquire new handles for async task.
170
+ let db = Arc :: clone ( & db) ;
171
+ let lock = Arc :: clone ( & lock) ;
172
172
173
- if !is_locked {
174
- // Acquire new handlers for async task.
175
- let db = Arc :: clone ( & db) ;
176
- let lock = Arc :: clone ( & lock) ;
177
-
178
- actix:: spawn ( async move {
179
- // Seal the escalation lock.
180
- lock. store ( true , Ordering :: Relaxed ) ;
173
+ actix:: spawn ( async move {
174
+ // Immediately exists if the lock cannot be acquired.
175
+ if let Ok ( locked) = lock. try_lock ( ) {
176
+ // Lock acquired and will remain locked until the
177
+ // handle goes out of scope.
178
+ let _l = locked;
181
179
182
180
match local ( db, escalation_window) . await {
183
181
Ok ( _) => { }
184
182
Err ( err) => error ! ( "{:?}" , err) ,
185
183
}
186
-
187
- // Unseal/unlock.
188
- lock. store ( false , Ordering :: Relaxed ) ;
189
- } ) ;
190
- }
184
+ }
185
+ } ) ;
191
186
} ,
192
187
) ;
193
188
}
0 commit comments