basic/
basic.rs

1use std::time::Duration;
2
3use polly_scheduler::core::{
4    context::TaskContext,
5    store::InMemoryTaskStore,
6    task::{Task, TaskFuture},
7    task_kind::TaskKind,
8};
9use serde::{Deserialize, Serialize};
10
11#[tokio::main]
12async fn main() {
13    tracing_subscriber::fmt()
14        .with_max_level(tracing::Level::INFO)
15        .init();
16
17    let task_store = InMemoryTaskStore::new();
18    let context = TaskContext::new(task_store)
19        .register::<MyTask1>()
20        .register::<MyTask2>()
21        .start();
22
23    context
24        .add_task(MyTask1::new("name1".to_string(), 32))
25        .await
26        .unwrap();
27
28    context
29        .add_task(MyTask2::new("name2".to_string(), 39))
30        .await
31        .unwrap();
32
33    tokio::time::sleep(Duration::from_secs(100000000)).await;
34}
35
36#[derive(Clone, Debug, Deserialize, Serialize)]
37struct MyTask1 {
38    pub name: String,
39    pub age: i32,
40}
41
42impl MyTask1 {
43    pub fn new(name: String, age: i32) -> Self {
44        Self { name, age }
45    }
46}
47
48impl Task for MyTask1 {
49    const TASK_KEY: &'static str = "my_task_a";
50
51    const TASK_QUEUE: &'static str = "default";
52
53    const TASK_KIND: TaskKind = TaskKind::Once;
54    //const RETRY_POLICY: RetryPolicy = RetryPolicy::linear(10, Some(5));
55
56    fn run(self) -> TaskFuture {
57        Box::pin(async move {
58            println!("{}", self.name);
59            println!("{}", self.age);
60
61            println!("my task1 is running");
62            Err("return error".to_string())
63        })
64    }
65}
66
67#[derive(Clone, Debug, Deserialize, Serialize)]
68struct MyTask2 {
69    pub name: String,
70    pub age: i32,
71}
72
73impl MyTask2 {
74    pub fn new(name: String, age: i32) -> Self {
75        Self { name, age }
76    }
77}
78
79impl Task for MyTask2 {
80    const TASK_KEY: &'static str = "my_task_b";
81    const TASK_QUEUE: &'static str = "default";
82    const TASK_KIND: TaskKind = TaskKind::Repeat;
83    const REPEAT_INTERVAL: Option<u32> = Some(10);
84    //const SCHEDULE: Option<&'static str> = Some("1/10 * * * * *");
85    //const TIMEZONE: Option<&'static str> = Some("Asia/Shanghai");
86
87    fn run(self) -> TaskFuture {
88        Box::pin(async move {
89            println!("{}", self.name);
90            println!("{}", self.age);
91            tokio::time::sleep(Duration::from_secs(100000)).await;
92            println!("my task2 is running");
93            Ok(())
94        })
95    }
96}