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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
use std::{
collections::HashMap,
sync::{Arc, RwLock},
};
use crate::{
error::PulsyncError,
recurrence::Recurrence,
scheduler::{Scheduler, TaskScheduler},
task::{
sync_task::{SyncTask, SyncTaskHandler},
TaskDetails, TaskId, TaskStatus,
},
};
impl TaskScheduler for Scheduler {
/// Create a new Asynchronous Scheduler.
fn build() -> Self {
Scheduler(Arc::new(RwLock::new(HashMap::<TaskId, SyncTask>::new())))
}
/// Add a task to the scheduler.
///
/// The task will be executed every `recurrence` time (according to the `unit` and `count`).
///
/// Do nothing if the task already exists in the scheduler.
///
/// # Example
/// ```rust,ignore
/// let id = scheduler.schedule(task, every(1.seconds())).unwrap();
/// ```
fn schedule(
&mut self,
task: Box<dyn SyncTaskHandler + Send + Sync + 'static>,
recurrence: Recurrence,
) -> Result<TaskId, PulsyncError> {
let id = task.unique_id(recurrence);
if self.read().unwrap().contains_key(&id) {
tracing::info!("[schedule] Task ({id}): already scheduled");
return Err(PulsyncError::AlreadyScheduled(id));
}
let status = Arc::new(RwLock::new(TaskStatus::Running));
let recurrence = Arc::new(RwLock::new(recurrence));
let title = Arc::new(task.title());
let created_at = chrono::Utc::now().naive_utc();
let _handle = {
let status = status.clone();
let recurrence = recurrence.clone();
let tasks = self.clone();
std::thread::spawn(move || {
{
if recurrence.clone().read().unwrap().run_after {
let duration = {
let read_guard = recurrence.read().unwrap();
read_guard.unit
};
std::thread::sleep(duration.into());
}
}
loop {
if *status.read().unwrap() == TaskStatus::Abort {
break;
}
{
let mut recurrence = recurrence.write().unwrap();
if let Some(limit) = recurrence.limit {
let now = chrono::Utc::now().naive_utc();
let elapsed_time = now - created_at;
if elapsed_time.num_seconds() as u64 >= *limit {
break;
}
}
if let Some(limit_datetime) = recurrence.limit_datetime {
if limit_datetime <= chrono::Utc::now().naive_utc() {
break;
}
}
match recurrence.count {
None => {}
Some(0) => break,
Some(count) => {
recurrence.count = Some(count - 1);
}
}
}
if *status.read().unwrap() == TaskStatus::Running {
task.run();
}
{
let duration = {
let read_guard = recurrence.read().unwrap();
read_guard.unit
};
std::thread::sleep(duration.into());
}
}
tasks.write().unwrap().remove(&id);
})
};
let task = SyncTask {
id,
created_at,
title,
status,
_handle,
recurrence,
};
self.write().unwrap().insert(task.id, task);
Ok(id)
}
/// Update the recurrence of a task.
///
/// Do nothing if the task does not exist in the scheduler.
///
/// # Example
/// ```rust,ignore
/// let id = scheduler.schedule(task, every(1.seconds())).unwrap();
/// let new_id = scheduler.reschedule(id, every(3.seconds())).unwrap();
/// ```
fn reschedule(&mut self, id: TaskId, recurrence: Recurrence) -> Result<TaskId, PulsyncError> {
let mut binding = self.write().unwrap();
let Some(task) = binding.get_mut(&id) else {
tracing::info!("[reschedule] Task ({id}): not found");
return Err(PulsyncError::TaskNotFound("reschedule", id));
};
*task.recurrence.write().unwrap() = recurrence;
Ok(id)
}
/// Pause the execution of a task.
///
/// Do nothing if the task doesn't exist in the scheduler or if the task is already paused.
///
/// # Example
/// ```rust,ignore
/// let id = scheduler.schedule(task, every(1.seconds())).unwrap();
/// scheduler.pause(id);
/// ```
fn pause(&mut self, id: TaskId) -> Result<(), PulsyncError> {
let mut binding = self.write().unwrap();
let Some(task) = binding.get_mut(&id) else {
tracing::info!("[pause] Task ({id}): not found");
return Err(PulsyncError::TaskNotFound("pause", id));
};
if *task.status.read().unwrap() == TaskStatus::Paused {
tracing::info!("[pause] Task ({id}): already paused");
return Err(PulsyncError::AlreadyPaused(id));
}
*task.status.write().unwrap() = TaskStatus::Paused;
Ok(())
}
/// Resume the execution of a task.
///
/// Do nothing if the task doesn't exist in the scheduler or if the task is already resumed.
///
/// # Example
/// ```rust,ignore
/// let id = scheduler.schedule(task, every(1.seconds())).unwrap();
/// scheduler.resume(id);
/// ```
fn resume(&mut self, id: TaskId) -> Result<(), PulsyncError> {
let mut binding = self.write().unwrap();
let Some(task) = binding.get_mut(&id) else {
tracing::info!("[resume] Task ({id}): not found");
return Err(PulsyncError::TaskNotFound("resume", id));
};
if *task.status.read().unwrap() == TaskStatus::Running {
tracing::info!("[resume] Task ({id}): already resumed");
return Err(PulsyncError::AlreadyResumed(id));
}
*task.status.write().unwrap() = TaskStatus::Running;
Ok(())
}
/// Abort the execution of a task. (The task will be removed from the scheduler)
///
/// Do nothing if the task doesn't exist in the scheduler.
///
/// # Example
/// ```rust,ignore
/// let id = scheduler.schedule(task, every(1.seconds())).unwrap();
/// scheduler.abort(id);
/// ```
fn abort(&mut self, id: TaskId) -> Result<(), PulsyncError> {
let mut binding = self.write().unwrap();
let Some(task) = binding.remove(&id) else {
tracing::info!("[abort] Task ({id}): not found");
return Err(PulsyncError::TaskNotFound("abort", id));
};
*task.status.write().unwrap() = TaskStatus::Abort;
Ok(())
}
/// Run a task once.
///
/// # Example
/// ```rust,ignore
/// scheduler.run(task);
/// ```
fn run(&self, task: impl SyncTaskHandler) {
std::thread::spawn(move || task.run());
}
/// Collect the title of all tasks in the scheduler.
///
/// # Example
/// ```rust,ignore
/// let titles = scheduler.get();
/// ```
fn get(&self) -> Vec<TaskDetails> {
self.read()
.unwrap()
.values()
.map(|task| TaskDetails {
id: task.id,
label: task.to_string(),
recurrence: task.recurrence.clone(),
status: *task.status.read().unwrap(),
created_at: task.created_at,
})
.collect()
}
#[cfg(feature = "serde")]
fn restart(
tasks: Vec<(Box<dyn SyncTaskHandler + Send + Sync + 'static>, Recurrence)>,
) -> (Self, Vec<Option<TaskId>>) {
let mut scheduler = Self::build();
let task_ids = tasks
.into_iter()
.map(|(task, recurrence)| scheduler.schedule(task, recurrence))
.collect::<Vec<Result<TaskId, PulsyncError>>>();
(scheduler, task_ids)
}
}