A simple, yet robust crate for managing asynchronous workers using tokio.
It allows you to define worker behaviors, dispatch messages to them, and
handle their replies asynchronously, all while ensuring graceful shutdown.
Features
- Asynchronous Message Passing: Utilize
tokio::mpscandtokio::oneshotchannels for efficient communication between your main application and workers. - Type-Safe Worker Management: Workers are identified by themself, ensuring strong type guarantees at compile time.
- Graceful Shutdown: The
WorkersManagerhandles the stopping of all managed workers, allowing them to finish ongoing tasks and perform cleanup. - Asynchronous Lifecycle Hooks: Workers can define
on_startandon_stopmethods to execute asynchronous initialization and cleanup logic. - Fire-and-Forget: Send messages without awaiting a reply when the response is not critical.
How to Use
- Define Your Worker: Implement the
Workertrait for your custom struct. This trait requires you to specify theWorkerMessage(the message type your worker expects) andWorkerReply(the response type it sends back).
use Future;
use Pin;
use ;
- Manage Workers with
WorkersManager: Create an instance ofWorkersManager, add your worker(s) to it, and then usesendorfire_sendto interact with them. Remember to callstop()for graceful shutdown.
use Future;
use Pin;
use ;
async
Important Note on Worker Uniqueness
The WorkersManager identifies workers by their types, allowing only one
instance of each type to be registered. To handle multiple workers of the
same type concurrently, implement a worker pool within the Worker's call
method. Contribution are welcome to support this feature.
Examples
Check out the examples directory for more examples.
Contributing
Contributions to tokio_worker are welcome! You can help by opening issues
(such as bug reports or feature requests) or submitting patches. All
contributions must be submitted through Nostr. For more details on the
process, please refer to the CONTRIBUTING.md file. Your support is greatly
appreciated!
License
This project is licensed under the MIT license for more details see the LICENSE file or http://opensource.org/licenses/MIT.