1
1
use std::time::Duration;
2

            
3
use budget_executor::asynchronous::singlethreaded::{Context, Progress};
4

            
5
#[tokio::main(flavor = "current_thread")]
6
1
async fn main() {
7
    // Run a task with no initial budget. The first time the task asks to spend
8
    // any budget, it will be paused.
9
1
    let mut progress = Context::run_with_budget(some_task_to_limit, 0).await;
10

            
11
    // At this point, the task has run until the first call to
12
    // budget_executor::spend. Because we gave an initial_budget of 0, the future
13
    // is now paused. Let's loop until it's finished, feeding it 5 budget at a
14
    // time.
15
    loop {
16
8
        progress = match progress {
17
7
            Progress::NoBudget(incomplete_task) => {
18
7
                // Resume the task, allowing for 5 more budget to be spent.
19
7
                println!("+5 budget");
20
7
                incomplete_task.continue_with_additional_budget(5).await
21
            }
22
1
            Progress::Complete(result) => {
23
1
                // The task has completed. `result.output` contains the output
24
1
                // of the task itself. We can also inspect the balance of the
25
1
                // budget:
26
1
                println!(
27
1
                    "Task completed with balance: {:?}, output: {:?}",
28
1
                    result.balance, result.output
29
1
                );
30
1
                break;
31
1
            }
32
1
        };
33
1
    }
34
1
}
35

            
36
1
async fn some_task_to_limit(context: Context<usize>) -> bool {
37
3
    do_some_operation(1, &context).await;
38
3
    do_some_operation(5, &context).await;
39
1
    do_some_operation(1, &context).await;
40
7
    do_some_operation(25, &context).await;
41
1
    true
42
1
}
43

            
44
4
async fn do_some_operation(times: u8, context: &Context<usize>) {
45
4
    println!("> Asking to spend {times} from the budget");
46
7
    context.spend(usize::from(times)).await;
47
7
    tokio::time::sleep(Duration::from_millis(u64::from(times) * 100)).await;
48
4
}
49

            
50
1
#[test]
51
1
fn runs() {
52
1
    main()
53
1
}