Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

timer

rust

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()
like image 354
Tkinter2 Avatar asked May 03 '16 16:05

Tkinter2


People also ask

What is threading timer in python?

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.

How do you stop a thread timer in python?

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.

Is timer a thread?

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!


2 Answers

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);
}
like image 196
malbarbo Avatar answered Nov 15 '22 10:11

malbarbo


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.

like image 23
Shepmaster Avatar answered Nov 15 '22 09:11

Shepmaster