Schedulable timer with asynchronous callback

Hi. I am new to Rust and I would like to know what is the best way to write a timer which:

  • after a defined amount of time executes an asynchronous callback
  • can be rescheduled/postponed (This means the caller can cancel the planned execution of the callback before it is executed and reschedule it with the same delay)

Thanks in advance

Naively, you would create a task (thread or async task) whose only responsibility is to sleep for the appropriate amount of time and then trigger the required event when it wakes after checking the cancelation condition.

With tokio, that's a combination of tokio::spawn() and CancellationToken. The example on this doc is pretty much exactly what you would do.

With std, it's std::thread::spawn() and AtomicBool.

There are also some abstractions built on these primitives, such as tokio::time::interval() and tokio_util::time::DelayQueue. And I've also seen some cron-like schedulers on crates.io.