Skip to content

Instantly share code, notes, and snippets.

@Jackzmc
Last active June 24, 2023 14:56
Show Gist options
  • Save Jackzmc/636109c876de7265c3f7b6e65f106937 to your computer and use it in GitHub Desktop.
Save Jackzmc/636109c876de7265c3f7b6e65f106937 to your computer and use it in GitHub Desktop.
Macros to easily create interval timers
#[macro_export]
/// Runs your code after Duration has passed
/// # Examples
/// ```
/// timeout!(Duration::from_seconds(15), {
/// println!("Shutting down now...")
/// });
/// ```
///
/// This is the same as:
/// ```
/// tokio::spawn(async move {
/// let mut timer = tokio::time::interval(Duration::from_seconds(15);
/// timer.tick().await;
/// //your function
/// })
/// ```
macro_rules! timeout {
( $i:expr, $x:expr) => {
{
tokio::spawn(async move {
tokio::time::sleep($i).await;
$x;
})
}
};
}
#[macro_export]
/// Creates a timer that calls a function every Duration
/// # Examples
/// ```
/// timer!(update_interval, {
/// let mut lock = manager.lock().await;
/// });
/// ```
///
/// This is the same as:
/// ```
/// tokio::spawn(async move {
/// let mut timer = tokio::time::interval(update_interval);
/// timer.tick().await;
/// loop {
/// timer.tick().await;
/// // your function
/// }
/// })
/// ```
macro_rules! timer {
( $i:expr, $x:expr) => {
{
tokio::spawn(async move {
let mut timer = tokio::time::interval($i);
timer.tick().await;
loop {
timer.tick().await;
$x;
}
})
}
};
}
#[macro_export]
/// Creates a timer that calls a function every Duration with an additional function called on start
///
/// See the [timer!] macro for more information
/// # Examples
/// ```
/// timer_start!(update_interval, {
/// println!("my timer is started!");
/// }, {
/// let mut lock = manager.lock().await;
/// });
/// ```
macro_rules! timer_start {
( $i:expr, $s:expr, $x:expr) => {
{
tokio::spawn(async move {
let mut timer = tokio::time::interval($i);
timer.tick().await;
$s;
loop {
timer.tick().await;
$x;
}
})
}
};
}
@Jackzmc
Copy link
Author

Jackzmc commented May 31, 2023

An example:

fn main() {
    timer_start!(cleanup_interval, {
        println!("[Cleanup] Cleaning messages every {} seconds", cleanup_interval.as_secs());
    }, {
        let mut lock = manager.lock().await;
        lock.cleanup();
    });
}

@kalenwallin
Copy link

This is really neat @Jackzmc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment