Run a task at a scheduled time

I want to make some sort of a reminder like feature, where I can do something after x amount of time. This x amount of time may span multiple days, and I'm assuming spawning a task that sleeps for 3 days isn't a great idea.

What are my options? Should I use some of the libraries that work as cron jobs? they seem to only do repeating tasks.

Bonus points if the solution survives a restart of the app.

Note that std::thread::sleep (and all the analogous async versions) do not count time while the computer is asleep. So if you start a timer for one hour, and put the computer to sleep after half an hour, the timer will not trigger until half an hour after it comes back from sleep.

I would probably make a task that checks the current time every minute, triggering once the desired instant has passed. If you have many tasks, you can put them in a BinaryHeap to always be able to peek the next thing that should be triggered.

would setting up a task that checks every minute be considered a good solution? and what would be a good way to survive complete shutdowns? saving the instant(s) to a file and loading them on startup?

Sure, I think checking every minute is fine. As for shutdowns, yes you will need to store them somewhere, e.g. a file or database.

Beside cron, there is "at", which is for running one-time tasks at specified time, so use that. If you need timer in your aplication, operating systems provide api for that. The easiest way to acces it would be to use it via Tokio ( ), but you could do it directly.

So tokio uses "at" for duration? didn't know that.
would async-std's sleep behave the same?

Tokio doesn't use an external program for timers. Note that @Fiedzia's link is to an old version.

At is Linux application, complementing cron, has nothing to do with tokio.

my bad :sweat_smile: I know about the at application. I misunderstood what you said and thought tokio uses the at application.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.