Cargo.toml
[dependencies]
hookmap = "0.4.7"
delay_timer = "0.10.1"main.rs
use hookmap::*;
use delay_timer::prelude::*;
use anyhow::Result;
use smol::Timer;
use std::time::Duration;
fn main() {
let hotkey = Hotkey::new();
hotkey!(hotkey => {
modifier(F1) {
//1、When I press F1,the timer start from 1 to 50000 millisecond. how to implement this.
//let mut current_time= 1;
//2、if the current_time equals some numbers, do somethings.
if current_time =2000 {
//do something 1
}
if current_time =39999 {
//do something 2
}
//...
}
});
hotkey.handle_input();
}发布于 2021-12-03 16:37:45
您可以将key_press of F1绑定到创建一个DelayTimer,该DelayTimer将在已定义的持续时间过后执行所需的各种任务。
以下代码将在每次按下F1键时创建一个单独的计时器。每个排定的任务将在2000年、39999和50000毫秒后打印一行。由于没有指定它,使用此解决方案,创建的任务的两个实例可能同时运行。
use hookmap::*;
use anyhow::Result;
use delay_timer::prelude::*;
use std::time::Duration;
use smol::Timer;
fn main() -> Result<()> {
let hotkey = Hotkey::new();
hotkey!(hotkey => {
on_press F1 => |_event| {
let delay_timer = DelayTimerBuilder::default().build();
// Create the task
// A chain of task instances.
let task_instance_chain = delay_timer.insert_task(build_task_async_print().unwrap()).unwrap();
// Get the running instance of task 1.
let task_instance = task_instance_chain.next_with_wait().unwrap();
// This while loop avoids removing the task before it completes
while task_instance.get_state() != delay_timer::prelude::instance::COMPLETED {};
// Remove task which id is 1.
delay_timer.remove_task(1).unwrap();
};
});
hotkey.handle_input();
Ok(())
}
// Actually build the task
fn build_task_async_print() -> Result<Task, TaskError> {
let mut task_builder = TaskBuilder::default();
// This is the function in which you want to wait
let body = create_async_fn_body!({
Timer::after(Duration::from_millis(2000)).await;
println!("First something");
Timer::after(Duration::from_millis(39999)).await;
println!("Second something");
Timer::after(Duration::from_millis(50000)).await;
println!("Timer end");
});
// Build the task and assign 1 to it
task_builder
.set_task_id(1)
.spawn(body)
}请注意,此解决方案只在Windows上工作,因为hookmap机箱只支持该操作系统。
https://stackoverflow.com/questions/70176848
复制相似问题