Struct asynchron::Futurize[][src]

pub struct Futurize<T, E> { /* fields omitted */ }
Expand description

Futurize task asynchronously.

Example:

 use asynchron::{Futurize, Progress};
 use std::time::{Duration, Instant};

 fn main() {
     let instant: Instant = Instant::now();

     let mut tasks = Vec::new();

     for i in 0..5 {
         let task = Futurize::task(i, move |cancel| -> Progress<u32, ()> {
             let millis = i + 1;
             let sleep_dur = Duration::from_millis((60 * millis).into());
             std::thread::sleep(sleep_dur);
             if cancel.load(std::sync::atomic::Ordering::Relaxed) {
                 return Progress::Canceled;
             } else {
                 return Progress::Completed(instant.elapsed().subsec_millis());
             }
         });
         tasks.push(task);
     }

     for task in tasks.iter() {
         task.try_do()
     }

     let mut task_count = tasks.len();
     loop {
         for task in tasks.iter() {
             if task.is_in_progress() {
                 match task.try_get() {
                     Progress::Current => {
                         if task.task_id() == 0 || task.task_id() == 3 {
                             task.cancel();
                         }
                         println!("task with id: {} is trying to be done\n", task.task_id());
                     }
                     Progress::Canceled =>  println!("task with id: {} is canceled\n", task.task_id()),
                     Progress::Completed(elapsed) => {
                         println!(
                             "task with id: {} elapsed at: {:?} milliseconds\n",
                             task.task_id(), elapsed
                         );
                     }
                     _ => (),
                 }

                 if task.is_done() {
                     task_count -= 1;
                 }
             }
         }

         if task_count == 0 {
             println!("all the tasks are done.");
             break;
         }
         std::thread::sleep(Duration::from_millis(50));
     }
 }

Implementations

Create new task.

Other Example:

use asynchron::{Futurize, Progress};
use std::{
    time::{Duration, Instant},
};

fn main() {
    let instant1: Instant = Instant::now();
    let mut task1_approx_dur = Duration::from_millis(400);

    let task1 = Futurize::task(0, move |_canceled| {
        std::thread::sleep(task1_approx_dur);
        let elapsed_content = format!(
           "instant 1 enlapsed by now {}",
            instant1.elapsed().subsec_millis()
        );
        // for Error demo, change the line above like so: (will return error)
        //
        // let elapsed_content = format!("notsparatedbyspace{}", instant1.elapsed().subsec_millis());
        let mut vec_ui32 = Vec::new();
        elapsed_content
            .split(" ")
            .for_each(|ch| match ch.trim().parse::<u32>() {
                Ok(ui32) => {
                    vec_ui32.push(ui32);
                    // for Cancelation demo
                    //
                    // if canceled.load(sync::atomic::Ordering) {
                    //     return Progress::Canceled;
                    // }
                }
                _ => (),
            });
        // and this, for Cancelation at the end of the tunnel
        //
        // if canceled.load(sync::atomic::Ordering) {
        //     return Progress::Canceled;
        // }
        if vec_ui32.len() > 0 {
            return Progress::Completed(vec_ui32);
        } else {
            return Progress::Error(
                "task 1 error:
                unable to parse u32
                at asynchron/example.rs on the line 20\n"
                    .to_string(),
            );
        }
    });
    task1.try_do();

    let mut task2_approx_dur = Duration::from_millis(600);
    let instant2: Instant = Instant::now();
    let task2 = Futurize::task(1, move |_| -> Progress<u32, ()> {
        std::thread::sleep(task2_approx_dur);
        return Progress::Completed(instant2.elapsed().subsec_millis());
    });
    task2.try_do();

    // let mut retry = 0;

    loop {
        if task1.is_in_progress() {
            match task1.try_get() {
                Progress::Current => {
                    println!("task 1 is trying to be done\n");
                }
                Progress::Canceled => println!("task 1 canceled"),
                Progress::Completed(value) => {
                    task1_approx_dur = instant1.elapsed();
                    println!(
                        "task 1 completed at: {:?} has value: {:?}\n",
                        task1_approx_dur, value
                    );
                    // task1.try_do();
                    // retry += 1;
                }
                Progress::Error(e) => println!("{}", e),
            }
        }

        // if retry == 0 {
        //     task1.cancel()
        // } else if retry > 1 {
        //     break;
        // }

        if task2.is_in_progress() {
            match task2.try_get() {
                Progress::Current => println!("task 2 is trying to be done\n"),
                Progress::Completed(value) => {
                    task2_approx_dur = instant2.elapsed();
                    println!(
                        "task 2 completed at: {:?} has value: {:?}\n",
                        task2_approx_dur, value
                    );
                    // task1.try_do();
                }
                _ => (),
            }
        }

        if task1.is_done() && task2.is_done() {
            break;
        }
        std::thread::sleep(Duration::from_millis(100));
    }
    let all_approxed_durs = task2_approx_dur + task1_approx_dur;
    println!(
        "all the tasks are done {:?} earlier.\n\nOk",
        all_approxed_durs - task2_approx_dur
    );
}

Try (it won’t block the current thread) to do the task now and then try to get the progress somewhere later on.

Cancel the task.

Check if the task is canceled.

Get the id of the task

Try to get the progress of the task, it won’t block current thread (non-blocking).

Check if the task is in progress.

Check if the task is completed.

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.