I'm looking for a timer which uses threads, not plain time.sleep
:
from threading import Timer
def x():
print "hello"
t = Timer(2.0, x)
t.start()
t = Timer(2.0, x)
t.start()
Introduction to Python Threading Timer. The timer is a subsidiary class present in the python library named “threading”, which is generally utilized to run a code after a specified time period. Python's threading. Timer() starts after the delay specified as an argument within the threading.
Python timer functions start() is a function that is used to initialize a timer. To end or quit the timer, one must use a cancel() function. Importing the threading class is necessary for one to use the threading class. The calling thread can be suspended for seconds using the function time.
The timer isn't a thread BUT having a timer fire events asynchronously can be regarded as a form of multi-threading - along with all the traditional multi-threading issues!
You can use the timer crate
extern crate timer;
extern crate chrono;
use timer::Timer;
use chrono::Duration;
use std::thread;
fn x() {
println!("hello");
}
fn main() {
let timer = Timer::new();
let guard = timer.schedule_repeating(Duration::seconds(2), x);
// give some time so we can see hello printed
// you can execute any code here
thread::sleep(::std::time::Duration::new(10, 0));
// stop repeating
drop(guard);
}
It's easy enough to write a similar version yourself, using only tools from the standard library:
use std::thread;
use std::time::Duration;
struct Timer<F> {
delay: Duration,
action: F,
}
impl<F> Timer<F>
where
F: FnOnce() + Send + Sync + 'static,
{
fn new(delay: Duration, action: F) -> Self {
Timer { delay, action }
}
fn start(self) {
thread::spawn(move || {
thread::sleep(self.delay);
(self.action)();
});
}
}
fn main() {
fn x() {
println!("hello");
let t = Timer::new(Duration::from_secs(2), x);
t.start();
}
let t = Timer::new(Duration::from_secs(2), x);
t.start();
// Wait for output
thread::sleep(Duration::from_secs(10));
}
As pointed out by malbarbo, this does create a new thread for each timer. This can be more expensive than a solution which reuses threads but it's a very simple example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With