#background-processing #tokio #jobs #processor #web-services #async-io

background-jobs-tokio

基于Tokio的进程内任务处理器

3个版本 (破坏性更新)

0.19.0 2024年7月9日
0.18.0 2024年2月5日
0.17.0 2024年1月18日

#441 in 异步

Download history 4/week @ 2024-04-22 3/week @ 2024-04-29 11/week @ 2024-05-20 2/week @ 2024-05-27 9/week @ 2024-06-03 3/week @ 2024-06-10 11/week @ 2024-06-17 21/week @ 2024-06-24 4/week @ 2024-07-01 153/week @ 2024-07-08 18/week @ 2024-07-15 16/week @ 2024-07-29 9/week @ 2024-08-05

每月51次下载
用于 2 个crate(通过 背景任务

AGPL-3.0

81KB
1.5K SLoC

背景任务

这个crate提供了从通常的同步应用程序异步运行某些进程所需的工具。标准的例子是Web服务,其中某些事物需要处理,但在用户等待浏览器响应时进行处理可能不是最佳体验。

用法

将背景任务添加到您的项目

[dependencies]
actix-rt = "2.2.0"
background-jobs = "0.15.0"
serde = { version = "1.0", features = ["derive"] }

要开始使用背景任务,首先您应该定义一个任务。

任务是由执行操作所需的数据和该操作的逻辑的组合。它们实现了Jobserde::Serializeserde::DeserializeOwned

use background_jobs::{Job, BoxError};
use std::future::{ready, Ready};

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct MyJob {
    some_usize: usize,
    other_usize: usize,
}

impl MyJob {
    pub fn new(some_usize: usize, other_usize: usize) -> Self {
        MyJob {
            some_usize,
            other_usize,
        }
    }
}

impl Job for MyJob {
    type State = ();
    type Error = BoxError;
    type Future = Ready<Result<(), BoxError>>;

    const NAME: &'static str = "MyJob";

    fn run(self, _: Self::State) -> Self::Future {
        info!("args: {:?}", self);

        ready(Ok(()))
    }
}

任务的run方法需要一个额外的参数,即任务期望使用的状态。应用程序中定义的所有任务的状态必须相同。默认情况下,状态是一个空元组,但您可能需要传递一些Actix地址或其他内容。

让我们重新定义任务以关注一些应用程序状态。

#[derive(Clone, Debug)]
pub struct MyState {
    pub app_name: String,
}

impl MyState {
    pub fn new(app_name: &str) -> Self {
        MyState {
            app_name: app_name.to_owned(),
        }
    }
}

impl Job for MyJob {
    type State = MyState;
    type Error = BoxError;
    type Future = Ready<Result<(), BoxError>>;

    // The name of the job. It is super important that each job has a unique name,
    // because otherwise one job will overwrite another job when they're being
    // registered.
    const NAME: &'static str = "MyJob";

    // The queue that this processor belongs to
    //
    // Workers have the option to subscribe to specific queues, so this is important to
    // determine which worker will call the processor
    //
    // Jobs can optionally override the queue they're spawned on
    const QUEUE: &'static str = DEFAULT_QUEUE;

    // The number of times background-jobs should try to retry a job before giving up
    //
    // Jobs can optionally override this value
    const MAX_RETRIES: MaxRetries = MaxRetries::Count(1);

    // The logic to determine how often to retry this job if it fails
    //
    // Jobs can optionally override this value
    const BACKOFF: Backoff = Backoff::Exponential(2);

    fn run(self, state: Self::State) -> Self::Future {
        info!("{}: args, {:?}", state.app_name, self);

        ready(Ok(()))
    }
}

运行任务

默认情况下,这个crate附带了启用background-jobs-actix功能。这使用background-jobs-actix crate启动服务器和工作者,并提供了一种生成新任务的机制。

background-jobs-actix本身没有存储工作者状态的机制。这可以通过手动实现background-jobs-core中的Storage trait来实现,或者可以使用提供的内存存储。

到此为止,回到示例

use background_jobs::{create_server, actix::WorkerConfig, BoxError};

#[actix_rt::main]
async fn main() -> Result<(), BoxError> {
    // Set up our Storage
    // For this example, we use the default in-memory storage mechanism
    use background_jobs::memory_storage::{ActixTimer, Storage};
    let storage = Storage::new(ActixTimer);

    // Configure and start our workers
    let queue_handle = WorkerConfig::new(storage, move || MyState::new("My App"))
        .register::<MyJob>()
        .set_worker_count(DEFAULT_QUEUE, 16)
        .start();

    // Queue our jobs
    queue_handle.queue(MyJob::new(1, 2))?;
    queue_handle.queue(MyJob::new(3, 4))?;
    queue_handle.queue(MyJob::new(5, 6))?;

    // Block on Actix
    actix_rt::signal::ctrl_c().await?;
    Ok(())
}
完整示例

对于完整示例项目,请参阅示例文件夹

提供自己的服务器/工作者实现

如果您想根据这个想法创建自己的任务处理器,可以依赖background-jobs-core crate,它提供了Job trait以及一些用于实现任务处理器和任务存储的有用类型。

贡献

对于您发现的任何问题,请随时提交问题。请注意,任何贡献的代码都将根据AGPLv3许可证授权。

许可证

版权 © 2022 Riley Trautman

background-jobs 是免费软件:您可以在自由软件基金会发布的GNU通用公共许可证的条款下重新分发和/或修改它,无论是许可证的第3版,还是(根据您的选择)任何较新版本。

background-jobs 分发时希望它是有用的,但没有任何保证;甚至没有关于适销性或特定用途适用性的暗示性保证。有关更多详细信息,请参阅GNU通用公共许可证。此文件是 background-jobs 的一部分。

您应该已经随 background-jobs 收到了GNU通用公共许可证的一份副本。如果没有,请参阅https://gnu.ac.cn/licenses/

依赖项

~5–7.5MB
~123K SLoC