Tkinter2
Tkinter2

Reputation: 83

Does Rust have an equivalent of Python's threading.Timer?

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()

Upvotes: 7

Views: 3735

Answers (2)

Shepmaster
Shepmaster

Reputation: 430663

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.

Upvotes: 7

malbarbo
malbarbo

Reputation: 11177

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);
}

Upvotes: 7

Related Questions