1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
use crate::results::AppResult;
use std::future::Future;
use std::time::Duration;
use tokio::task::{JoinHandle, spawn_blocking};
use tokio::{spawn, time};
use tracing::error;
pub struct Tokio;
impl Tokio {
pub async fn run_blocking<Func, Ret>(func: Func) -> AppResult<Ret>
where
Func: FnOnce() -> Ret + Send + 'static,
Ret: Send + 'static,
{
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
Ok(rt.spawn_blocking(func).await?)
}
///
///
/// # Arguments
///
/// * `interval`: an interval within which the given function will be executed (in milliseconds)
/// * `func`: The function that will be executed
///
/// returns: ()
///
/// # Examples
///
/// ```
///
/// ```
pub fn timeout<Fun, Fut>(interval: u64, func: Fun, name: &str)
where
Fun: FnOnce() -> Fut + Send + 'static,
Fut: Future<Output = AppResult<()>> + Send + 'static,
{
let name = name.to_owned();
spawn(async move {
let mut interval = time::interval(Duration::from_millis(interval));
interval.tick().await;
interval.tick().await;
match func().await {
Ok(_) => {}
Err(err) => {
error!("[execution-error][{name}] {err:?}");
}
}
});
}
///
///
/// # Arguments
///
/// * `interval`: an interval within which the given function will be executed (in milliseconds)
/// * `func`: the function that will be executed repeatedly
///
/// returns: ()
///
/// # Examples
///
/// ```
///
/// ```
pub fn tick<Fun, Fut>(interval: u64, func: Fun, name: &str)
where
Fun: Fn() -> Fut + Send + 'static,
Fut: Future<Output = AppResult<()>> + Send + 'static,
{
let name = name.to_owned();
spawn(async move {
let mut interval = time::interval(Duration::from_millis(interval));
loop {
interval.tick().await;
match func().await {
Ok(_) => {}
Err(err) => {
error!("[execution-error][{name}] {err:?}");
}
}
}
});
}
pub fn blk<F, R>(f: F) -> JoinHandle<R>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
spawn_blocking(f)
}
}