#loops #check #execution #thread #executed #exit #closures

bin+lib time-check-loop

add a README.md

2 releases

0.1.1 Jun 3, 2023
0.1.0 Jun 3, 2023

#13 in #executed

MIT license

9KB
78 lines

将一个需要执行的函数当作闭包传递到子线程中循环执行,

Pass a function that needs to be executed as a closure to a child thread for loop execution,

循环的同时有一个时间循环的线程配套,

At the same time as the loop, there is a time loop thread matching,

需要执行的函数每执行一次,会更新一次执行时间

The execution time of the function that needs to be executed is updated every time it is executed

时间循环函数一次sleep时间为time_check,执行时间距离上次执行时间大于四倍time_check则退出循环

The time loop function has a sleep time of time_ Check, the execution time is greater than four times the last execution time_ Check to exit the loop

注意如果执行的函数中有阻塞(例如io输入),会发生时间循环子线程退出,函数执行循环子线程一直在等待直到有IO输入或者main函数退出

Note that if there is a block in the executed function (such as IO input), a time loop sub thread will exit, and the function execution loop sub thread will wait until there is IO input or the main function exits

Example

 use std::thread;
 use std::time::Duration;
 //需要循环一次的函数
 //Functions that need to be iterated once
fn text_fn(i:u64) {
    let mut buffer = String::new();
    std::io::stdin().read_line(&mut buffer).unwrap();
    println!("text is {}",buffer);
    thread::sleep(Duration::from_secs(i));
    }
fn main() {   
    let time_check = 5;//单位为秒  Unit in seconds
      thread::spawn ( 
         move|| {
              time_check_loop::loop_time_check(move || {text_fn(1);},time_check); 
        }
     );
    loop{
    thread::sleep(Duration::new(5,0));
     };
}

No runtime deps