Running a function in the background

I've been trying to figure out how to solve a problem, but to no avail - so I'll pose it here:
All I want to do is send an email after a user has invited someone to an event. However, I don't want to wait for the email to be send before telling the user the invite was created successfully (on invite, the database is updated so the invitee will see it on next login).

Thus, I tried to use tokio's task system to task::spawn the function that sends the email from the function that tells the user the invite was successful. I'm using, and when I tried to put #[tokio::main] above my main function, I got an error about task::spawn having to be called from the context of a tokio runtime.

Surely there must be a simpler way of doing this than trial and error putting #[tokio::main] on top of each function in my program until tokio executes the code. I've looked into clokwerk as well, but that seems to be for scheduling recurring tasks (e.g. once per week), not one-off tasks such as notification emails.

Thanks in advance for any help.

If you aren't already using async and tokio, I don't think adding it for this one task is ideal. It's probably easeir to just call std::thread::spawn with your task and ignore/drop the JoinHandle.

You could also spawn a emailer actor thread before starting the Rocket server which loops over a message queue and sends emails for each message, and then just dispatch a message to the queue when you want something emailed.

Are you using Rocket from They haven't published an async compatible version yet. I bet the threads that run the request handlers aren't part of the tokio runtime. That would mean that you can't spawn tasks. They are also on an older version of tokio so things might work differently if you are reading the current tokio docs.

Yeah the current version of rocket isn't async enabled.

I've found that tokio gets very confused when you create new instances of the runtime, but using the current handle to spawn things worked for me.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.