basic/
basic.rs

1use std::time::Duration;
2
3use persistent_scheduler::core::{
4    context::{TaskConfiguration, 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        .set_concurrency("default", 10)
22        .start()
23        .await;
24    let mut tasks = Vec::new();
25    for _ in 0..100 {
26        tasks.push(TaskConfiguration {
27            inner: MyTask1::new("name1".to_string(), 32),
28            kind: TaskKind::Once,
29            delay_seconds: None,
30        });
31    }
32
33    tokio::spawn(async move {
34        context.add_tasks(tasks).await.unwrap();
35    });
36    tokio::time::sleep(Duration::from_secs(20)).await;
37    
38}
39
40#[derive(Clone, Debug, Deserialize, Serialize)]
41struct MyTask1 {
42    pub name: String,
43    pub age: i32,
44}
45
46impl MyTask1 {
47    pub fn new(name: String, age: i32) -> Self {
48        Self { name, age }
49    }
50}
51
52impl Task for MyTask1 {
53    const TASK_KEY: &'static str = "my_task_a";
54
55    const TASK_QUEUE: &'static str = "default";
56
57    fn run(self) -> TaskFuture {
58        Box::pin(async move {
59            // println!("{}", self.name);
60            // println!("{}", self.age);
61            //tokio::time::sleep(Duration::from_secs(15)).await;
62            // println!("my task1 is running");
63            Ok(())
64        })
65    }
66}
67
68#[derive(Clone, Debug, Deserialize, Serialize)]
69struct MyTask2 {
70    pub name: String,
71    pub age: i32,
72}
73
74impl MyTask2 {
75    pub fn new(name: String, age: i32) -> Self {
76        Self { name, age }
77    }
78}
79
80impl Task for MyTask2 {
81    const TASK_KEY: &'static str = "my_task_b";
82    const TASK_QUEUE: &'static str = "default";
83
84    fn run(self) -> TaskFuture {
85        Box::pin(async move {
86            println!("{}", self.name);
87            println!("{}", self.age);
88            tokio::time::sleep(Duration::from_secs(100000)).await;
89            println!("my task2 is running");
90            Ok(())
91        })
92    }
93}