@@ -6,8 +6,12 @@ use std::sync::Arc;
6
6
use std:: time:: Duration ;
7
7
8
8
use tokio:: sync:: mpsc;
9
+ use tokio:: task:: JoinHandle ;
9
10
use tokio:: time:: sleep_until;
10
11
use tokio:: time:: Instant ;
12
+ use tracing:: Instrument ;
13
+ use tracing:: Level ;
14
+ use tracing:: Span ;
11
15
12
16
use crate :: raft:: RaftMsg ;
13
17
use crate :: NodeId ;
@@ -55,11 +59,12 @@ where
55
59
tx : mpsc:: UnboundedSender < RaftMsg < C , N , S > > ,
56
60
57
61
/// Emit event or not
58
- running : Arc < AtomicBool > ,
62
+ enabled : Arc < AtomicBool > ,
59
63
}
60
64
61
65
pub ( crate ) struct TickHandle {
62
- running : Arc < AtomicBool > ,
66
+ enabled : Arc < AtomicBool > ,
67
+ join_handle : JoinHandle < ( ) > ,
63
68
}
64
69
65
70
impl < C , N , S > Tick < C , N , S >
@@ -68,12 +73,16 @@ where
68
73
N : RaftNetworkFactory < C > ,
69
74
S : RaftStorage < C > ,
70
75
{
71
- pub ( crate ) fn new ( interval : Duration , tx : mpsc:: UnboundedSender < RaftMsg < C , N , S > > , enabled : bool ) -> Self {
72
- Tick {
76
+ pub ( crate ) fn spawn ( interval : Duration , tx : mpsc:: UnboundedSender < RaftMsg < C , N , S > > , enabled : bool ) -> TickHandle {
77
+ let enabled = Arc :: new ( AtomicBool :: from ( enabled) ) ;
78
+ let this = Self {
73
79
interval,
74
- running : Arc :: new ( AtomicBool :: from ( enabled) ) ,
80
+ enabled : enabled. clone ( ) ,
75
81
tx,
76
- }
82
+ } ;
83
+ let join_handle =
84
+ tokio:: spawn ( this. tick_loop ( ) . instrument ( tracing:: span!( parent: & Span :: current( ) , Level :: DEBUG , "tick" ) ) ) ;
85
+ TickHandle { enabled, join_handle }
77
86
}
78
87
79
88
pub ( crate ) async fn tick_loop ( self ) {
84
93
let at = Instant :: now ( ) + self . interval ;
85
94
sleep_until ( at) . await ;
86
95
87
- if !self . running . load ( Ordering :: Relaxed ) {
96
+ if !self . enabled . load ( Ordering :: Relaxed ) {
88
97
i -= 1 ;
89
98
continue ;
90
99
}
@@ -97,17 +106,14 @@ where
97
106
}
98
107
}
99
108
}
100
-
101
- /// Return a handle to control the ticker.
102
- pub ( crate ) fn get_handle ( & self ) -> TickHandle {
103
- TickHandle {
104
- running : self . running . clone ( ) ,
105
- }
106
- }
107
109
}
108
110
109
111
impl TickHandle {
110
112
pub ( crate ) fn enable ( & self , enabled : bool ) {
111
- self . running . store ( enabled, Ordering :: Relaxed ) ;
113
+ self . enabled . store ( enabled, Ordering :: Relaxed ) ;
114
+ }
115
+
116
+ pub ( crate ) async fn shutdown ( & self ) {
117
+ self . join_handle . abort ( ) ;
112
118
}
113
119
}
0 commit comments