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 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
extern crate chrono;
extern crate cron;
use crate::task::Status::Init;
use chrono::TimeZone;
use chrono::{DateTime, Utc};
use cron::Schedule;
use log::{debug, error, warn};
use tokio::sync::{mpsc, oneshot};
/// An executable function.
pub type ExecutableFn = dyn FnMut() -> Result<(), ()> + 'static + Send;
/// A task step.
///
/// Contains the executable body and an optional short description.
pub struct TaskStep {
/// The function's body.
pub(crate) function: Box<ExecutableFn>,
/// An (optional) short description.
pub(crate) description: Option<String>,
}
impl TaskStep {
/// Default constructor.
///
/// # Arguments
///
/// * description - a description for the task step
/// * function - the executable body of the function
///
/// # Examples
///
/// ```
/// # use tasklet::task::TaskStep;
/// let _ = TaskStep::new("Some task", || Ok(()));
/// ```
pub fn new<F>(description: &str, function: F) -> Self
where
F: (FnMut() -> Result<(), ()>) + 'static + Send,
{
Self {
description: Some(description.to_string()),
function: Box::new(function),
}
}
/// Default constructor for a task step without a provided description.
///
/// # Arguments
///
/// *function -> the executable function body
///
/// # Examples
///
/// ```
/// # use tasklet::task::TaskStep;
///
/// let _ = TaskStep::default(|| {Ok(())});
/// ```
pub fn default<F>(function: F) -> Self
where
F: (FnMut() -> Result<(), ()>) + 'static + Send,
{
Self {
function: Box::new(function),
description: None,
}
}
}
/// Available task statuses.
#[derive(Debug, PartialEq, Default, Clone)]
pub enum Status {
#[default]
/// The task is not initialized yet.
Init,
/// The task has been scheduled and pending execution.
Scheduled,
/// The task has executed but has failed.
Failed,
/// The task has executed successfully.
Executed,
/// The task has finished and can be removed from the queue
Finished,
}
/// A message response from a task
#[derive(Debug)]
pub(crate) struct TaskResponse {
/// The id of the task as set by the scheduler
pub id: usize,
/// The status after the request has been fulfilled
pub status: Status,
}
#[derive(Debug)]
/// Available commands to be sent
pub(crate) enum TaskCmd {
/// Request to initialize the task
Init {
sender: oneshot::Sender<TaskResponse>,
},
/// Execute the task
Run {
sender: oneshot::Sender<TaskResponse>,
},
/// Request the rescheduling of the task
Reschedule {
sender: oneshot::Sender<TaskResponse>,
},
}
/// A structure that contains the basic information of the job.
pub struct Task<T>
where
T: TimeZone + Send + 'static,
{
/// Task's executable tasks.
pub(crate) steps: Vec<TaskStep>,
/// The execution schedule.
pub(crate) schedule: Schedule,
/// Total number of executions, if `None` then it will run forever.
pub(crate) repeats: Option<usize>,
/// (Optional) Task's description.
pub(crate) description: String,
/// The timezone of the task.
pub(crate) timezone: T,
/// (Internal) task id.
pub(crate) task_id: usize,
/// (Internal) next execution time.
pub(crate) next_exec: Option<DateTime<T>>,
/// (Internal) task status.
pub(crate) status: Status,
/// Task receiver
pub(crate) receiver: Option<mpsc::Receiver<TaskCmd>>,
}
unsafe impl<T> Send for Task<T> where T: TimeZone + Send + 'static {}
impl<T> Task<T>
where
T: TimeZone + Send + 'static,
{
/// Create a new instance of type `Task`.
///
/// # Arguments
///
/// * expression - A valid cron expression.
/// * description - (Optional) description.
/// * repeats - maximum number of repeats, if `None` this task will run forever.
/// * timezone - The tasks' timezone.
///
/// # Examples
///
/// ```
/// # use tasklet::Task;
/// // Create a new task instance. This task will execute every second for 5 times.
/// let _task = Task::new("* * * * * * * ", Some("Runs every second!"), Some(5), chrono::Utc);
/// ```
/// ```
/// # use tasklet::Task;
/// // Create a new task instance. This task will run on second 30 of each minute forever.
/// let _task_1 = Task::new("30 * * * * * *", Some("Runs every second 30 of a minute!"), None, chrono::Local);
/// ```
pub fn new(
expression: &str,
description: Option<&str>,
repeats: Option<usize>,
timezone: T,
) -> Task<T> {
Task {
steps: Vec::new(),
schedule: expression.parse().unwrap(),
description: match description {
Some(s) => s.to_string(),
None => "-".to_string(),
},
repeats,
timezone,
task_id: 0,
status: Status::default(),
next_exec: None,
receiver: None,
}
}
pub(crate) fn set_receiver(&mut self, receiver: mpsc::Receiver<TaskCmd>) {
self.receiver = Some(receiver);
}
/// Set the task id of the current task.
///
/// # Arguments
///
/// * id - the id of the task
///
/// # Examples
///
/// ```
/// # use chrono::Utc;
/// # use tasklet::task::Task;
///
/// let mut t = Task::new("* * * * * *", None, None, Utc);
/// t.set_id(0);
/// ```
pub fn set_id(&mut self, id: usize) {
self.task_id = id;
}
/// Add a new `TaskStep` in the `Task`.
///
/// # Arguments
///
/// * description - A short task step description (Optional).
/// * function - The executable function.
#[cfg(test)]
pub(crate) fn add_step<F>(&mut self, description: &str, function: F) -> &mut Task<T>
where
F: (FnMut() -> Result<(), ()>) + 'static + Send,
{
self.steps.push(TaskStep::new(description, function));
self
}
/// Add a new `TaskStep` in the `Task` without a provided name/description.
///
/// # Arguments
///
/// * function - the executable function
#[cfg(test)]
pub(crate) fn add_step_default<F>(&mut self, function: F) -> &mut Task<T>
where
F: (FnMut() -> Result<(), ()>) + 'static + Send,
{
self.steps.push(TaskStep::default(function));
self
}
/// Set the value of the steps vector.
///
/// # Arguments
///
/// * steps - A vector that contains the executable steps.
pub(crate) fn set_steps(&mut self, steps: Vec<TaskStep>) -> &mut Task<T> {
self.steps = steps;
self
}
/// Set the value of `schedule` property.
///
/// # Arguments
///
/// * schedule - The schedule.
pub(crate) fn set_schedule(&mut self, schedule: Schedule) -> &mut Task<T> {
self.schedule = schedule;
self
}
/// Initialize the `Task` instance and schedule the first execution.
///
/// # Arguments
///
/// * id - The task's id.
pub(crate) fn init(&mut self) {
debug!("Task with id {} is initializing.", self.task_id);
self.next_exec = Some(
self.schedule
.upcoming(self.timezone.clone())
.next()
.unwrap(),
);
self.status = Status::Scheduled;
debug!("Task with id {} finished initializing.", self.task_id);
}
/// Create a `TaskResponse` from the current state of the task.
fn get_task_response(&self) -> TaskResponse {
TaskResponse {
id: self.task_id,
status: self.status.clone(),
}
}
/// Execute a command sent by the scheduler.
///
/// Each of the commands triggers the underlying method of the task,
/// and responds with the id of the task and the status of the task after the execution
/// of the command has finished.
pub(crate) fn execute_command(&mut self, msg: TaskCmd) {
match msg {
TaskCmd::Run { sender } => {
if self.next_exec.as_ref().unwrap()
<= &Utc::now().with_timezone(&self.timezone.clone())
{
self.run_task();
}
let _ = sender.send(self.get_task_response());
}
TaskCmd::Reschedule { sender } => {
self.reschedule();
let _ = sender.send(self.get_task_response());
}
TaskCmd::Init { sender } => {
if self.status == Init {
self.init();
}
let _ = sender.send(self.get_task_response());
}
}
}
/// Run the task and handle the output.
pub(crate) fn run_task(&mut self) {
match &self.status {
Status::Init => panic!("Task not initialized yet!"),
Status::Failed => panic!("Task must be rescheduled!"),
Status::Executed => panic!("Task already executed and must be rescheduled!"),
Status::Finished => panic!("Task has finished and must be removed!"),
Status::Scheduled => {
debug!(
"[Task {}] [{}] is been executed...",
self.task_id, self.description
);
let mut had_error: bool = false;
for (index, step) in self.steps.iter_mut().enumerate() {
if !had_error {
match (step.function)() {
Ok(_) => {
debug!(
"[Task {}-{}] [{:?}] Executed successfully.",
self.task_id, index, step.description,
);
self.status = Status::Executed
}
Err(_) => {
error!(
"[Task {}-{}] [{:?}] Execution failed.",
self.task_id, index, step.description,
);
// Indicate that there was an error.
had_error = true;
self.status = Status::Failed
}
};
}
}
// Avoid underflow in case of a task without steps.
if self.steps.is_empty() {
self.status = Status::Executed
}
// Reduce the total executions (if set).
self.repeats = self.repeats.map(|r| r - 1);
}
}
}
/// Reschedule the current task instance (if needed).
pub(crate) fn reschedule(&mut self) {
match &self.status {
Status::Init => panic!("Task not initialized yet!"),
Status::Failed | Status::Executed => {
self.next_exec = Some(
self.schedule
.upcoming(self.timezone.clone())
.next()
.unwrap(),
);
self.status = match self.repeats {
Some(t) => {
if t > 0 {
debug!("[Task {}] Has been rescheduled.", self.task_id);
Status::Scheduled
} else {
warn!(
"[Task {}] Has finished its execution cycle and will be removed.",
self.task_id
);
Status::Finished
}
}
None => Status::Scheduled,
}
}
Status::Finished => panic!("[Task {}] has finished and must be removed!", self.task_id),
Status::Scheduled => { /* Do nothing */ }
}
}
}
/// Wrap a `Task` around a receiver, each time a command is received, forward it to the task.
///
/// # Arguments
///
/// * task - the task to run in the background
///
/// # Examples
///
/// ```
/// # use chrono::Utc;
/// # use tasklet::task::Task;
/// # use tasklet::task::run_task;
/// # tokio_test::block_on( async {
/// let t = Task::new("* * * * * *", None, None, Utc);
/// let h = tokio::spawn(run_task(t));
/// # h.abort();
/// # })
/// ```
pub async fn run_task<T>(mut task: Task<T>)
where
T: TimeZone + Send + 'static,
{
while let Some(msg) = task
.receiver
.as_mut()
.expect("Failed to borrow receiver.")
.recv()
.await
{
task.execute_command(msg);
}
}
#[cfg(test)]
mod test {
use super::*;
use chrono::prelude::*;
#[test]
fn normal_task_flow_test() {
let mut task = Task::new("* * * * * *", Some("Test task"), Some(2), Local);
task.add_step_default(|| Ok(()));
assert_eq!(task.status, Status::Init);
task.set_id(0);
task.init();
assert_eq!(task.status, Status::Scheduled);
task.run_task();
assert_eq!(task.status, Status::Executed);
task.reschedule();
assert_eq!(task.status, Status::Scheduled);
task.run_task();
assert_eq!(task.status, Status::Executed);
task.reschedule();
assert_eq!(task.status, Status::Finished);
}
#[test]
fn test_task_set_schedule() {
let schedule: Schedule = "* * * * * * *".parse().unwrap();
let mut task = Task::new("* * * * * * *", None, None, Local);
task.set_schedule(schedule);
task.add_step_default(|| Ok(()));
assert_eq!(task.status, Status::Init);
task.set_id(0);
task.init();
assert_eq!(task.status, Status::Scheduled);
}
#[test]
fn normal_task_error_flow_test() {
let mut task = Task::new("* * * * * *", Some("Test task"), Some(2), Local);
task.add_step_default(|| Err(()));
assert_eq!(task.status, Status::Init);
task.set_id(0);
task.init();
assert_eq!(task.status, Status::Scheduled);
task.run_task();
assert_eq!(task.status, Status::Failed);
task.reschedule();
assert_eq!(task.status, Status::Scheduled);
task.run_task();
assert_eq!(task.status, Status::Failed);
task.reschedule();
assert_eq!(task.status, Status::Finished);
}
/// Test the normal execution of a simple task, without fixed repeats.
#[test]
fn normal_task_no_fixed_repeats_test() {
let mut task = Task::new("* * * * * * *", Some("Test task"), None, Local);
task.add_step_default(|| Ok(()));
assert_eq!(task.status, Status::Init);
task.set_id(0);
task.init();
assert_eq!(task.status, Status::Scheduled);
// Run it for a few times.
for _i in 1..10 {
task.run_task();
assert_eq!(task.status, Status::Executed);
task.reschedule();
assert_eq!(task.status, Status::Scheduled);
}
}
#[test]
#[should_panic(expected = "Task not initialized yet!")]
fn test_reschedule_init_panic() {
let mut task = Task::new("* * * * * * *", None, None, Local);
// This task is not initialized, so it should fail.
task.reschedule();
}
#[test]
#[should_panic(expected = "[Task 0] has finished and must be removed!")]
fn test_reschedule_finished_panic() {
let mut task = Task::new("* * * * * * *", None, Some(1), Local);
// Execute the task.
task.set_id(0);
task.init();
task.run_task();
task.reschedule();
// Try to reschedule after it's finished. It should fail.
task.reschedule();
}
#[test]
#[should_panic = "Task not initialized yet!"]
fn test_run_uninitialized_task() {
let mut task = Task::new("* * * * * * *", None, None, Local);
task.run_task();
}
#[test]
#[should_panic = "Task must be rescheduled!"]
fn test_run_failed_task() {
let mut task = Task::new("* * * * * * *", None, None, Local);
task.add_step_default(|| Err(()));
task.set_id(0);
task.init();
task.run_task();
// Attempt to rerun it, it should fail.
task.run_task();
}
#[test]
#[should_panic = "Task already executed and must be rescheduled!"]
fn test_run_executed_task() {
let mut task = Task::new("* * * * * * *", None, None, Local);
task.add_step("Step 1", || Ok(()));
task.set_id(0);
task.init();
task.run_task();
// Attempt to run it again, it should fail.
task.run_task();
}
#[test]
#[should_panic = "Task has finished and must be removed!"]
fn test_run_finished_task() {
let mut task = Task::new("* * * * * * *", None, Some(1), Local);
task.set_id(0);
task.init();
task.run_task();
task.reschedule();
// At this point the task is Finished. It should not be allowed to run again.
task.run_task();
}
}