windowswinapirusttimeroperating-system

Schedule wakeup with WinAPI in Rust


I'm trying to write alarm clock program that will wakeup the computer at specific time from hibernation/sleep or shutdown and make the alarm sound.

I created the following functions:

use crate::args::Args;
use eyre::Result;
use std::time::Duration;

#[cfg(windows)]
pub fn scheduled_wakeup(schedule: Duration) -> Result<()> {
  use windows::Win32::Foundation::HANDLE;
  use windows::Win32::System::Threading::{
    CreateWaitableTimerW, SetWaitableTimer, WaitForSingleObject, INFINITE,
  };

  // Due time in 100-nanosecond intervals (negative for relative time)
  let due_time = -(schedule.as_secs() as i64 * 10_000_000);
  unsafe {
    let timer: HANDLE = CreateWaitableTimerW(None, true, None)?;
    SetWaitableTimer(
      timer, &due_time, 0, // One-time timer
      None, None, true, // Resume from sleep
    )?;
    WaitForSingleObject(timer, INFINITE);
  };
  Ok(())
}

With the following dependencies:

windows = { version = "0.58.0", features = [
    "Win32",
    "Win32_Security",
    "Win32_System",
    "Win32_System_Threading",
] }

But when I run the program and turn it into sleep mode, it doesn't turn on after a minute. Also, how can I do it in a way that the event will be declared as "important" so it will work if the power setting was set like that? -

enter image description here

I can see that it scheduled in

powercfg -waketimers

But still, it doesn't turn on the PC


Solution

  • Turns out the code works. I needed to enable non important timers to wakeup the computer by opening control powercfg.cpl,,3 -> Sleep -> Allow wake timers -> Enable instead of Important only. I'm wondering now how can I configure the timer to be considered as important