1
0
Fork
You've already forked background-jobs
0
  • Rust 99.4%
  • Nix 0.5%
  • Shell 0.1%
2026年01月13日 15:14:33 -06:00
.cargo Start building jobs-postgres 2024年01月09日 23:16:35 -06:00
examples Job: remove associated future type, actix: remove 'server', all: rename QueueHandle, fix docs 2026年01月13日 15:14:33 -06:00
jobs-actix Job: remove associated future type, actix: remove 'server', all: rename QueueHandle, fix docs 2026年01月13日 15:14:33 -06:00
jobs-core Job: remove associated future type, actix: remove 'server', all: rename QueueHandle, fix docs 2026年01月13日 15:14:33 -06:00
jobs-metrics metrics: remove async-trait 2026年01月12日 11:55:58 -06:00
jobs-postgres postgres: diesel 2.3 2026年01月11日 22:47:09 -06:00
jobs-sled Job: remove associated future type, actix: remove 'server', all: rename QueueHandle, fix docs 2026年01月13日 15:14:33 -06:00
jobs-tokio Job: remove associated future type, actix: remove 'server', all: rename QueueHandle, fix docs 2026年01月13日 15:14:33 -06:00
scripts Start building jobs-postgres 2024年01月09日 23:16:35 -06:00
src Job: remove associated future type, actix: remove 'server', all: rename QueueHandle, fix docs 2026年01月13日 15:14:33 -06:00
.gitignore Check-in Cargo.lock 2026年01月11日 22:50:19 -06:00
Cargo.lock Remove thiserror 2026年01月12日 12:46:25 -06:00
Cargo.toml metrics 0.24, use async-trait less 2026年01月11日 22:39:42 -06:00
flake.lock nixos 25.11 2026年01月11日 22:18:36 -06:00
flake.nix nixos 25.11 2026年01月11日 22:18:36 -06:00
LICENSE Relicense 2021年09月21日 10:17:24 -05:00
README.md Job: remove associated future type, actix: remove 'server', all: rename QueueHandle, fix docs 2026年01月13日 15:14:33 -06:00

Background Jobs

This crate provides tooling required to run some processes asynchronously from a usually synchronous application. The standard example of this is Web Services, where certain things need to be processed, but processing them while a user is waiting for their browser to respond might not be the best experience.

Usage

Add Background Jobs to your project

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

To get started with Background Jobs, first you should define a job.

Jobs are a combination of the data required to perform an operation, and the logic of that operation. They implement the Job, serde::Serialize, and serde::DeserializeOwned.

usebackground_jobs::{Job,BoxError};#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]pubstruct MyJob{some_usize: usize,other_usize: usize,}implMyJob{pubfn new(some_usize: usize,other_usize: usize)-> Self{MyJob{some_usize,other_usize,}}}implJobforMyJob{type State=();type Error=BoxError;constNAME: &'static str ="MyJob";asyncfn run(self,_: Self::State)-> Result<(),Self::Error>{info!("args: {:?}",self);Ok(())}}

The run method for a job takes an additional argument, which is the state the job expects to use. The state for all jobs defined in an application must be the same. By default, the state is an empty tuple, but it's likely you'll want to pass in some Actix address, or something else.

Let's re-define the job to care about some application state.

#[derive(Clone, Debug)]pubstruct MyState{pubapp_name: String,}implMyState{pubfn new(app_name: &str)-> Self{MyState{app_name: app_name.to_owned(),}}}implJobforMyJob{type State=MyState;type Error=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.
constNAME: &'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
constQUEUE: &'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
constMAX_RETRIES: MaxRetries=MaxRetries::Count(1);// The logic to determine how often to retry this job if it fails
//
// Jobs can optionally override this value
constBACKOFF: Backoff=Backoff::Exponential(2);asyncfn run(self,state: Self::State)-> Result<(),Self::Error>{info!("{}: args, {:?}",state.app_name,self);Ok(())}}

Running jobs

By default, this crate ships with the background-jobs-actix feature enabled. This uses the background-jobs-actix crate to spin up a Server and Workers, and provides a mechanism for spawning new jobs.

background-jobs-actix on it's own doesn't have a mechanism for storing worker state. This can be implemented manually by implementing the Storage trait from background-jobs-core, or the provided in-memory store can be used.

With that out of the way, back to the examples:

Main
usebackground_jobs::{create_server,actix::WorkerConfig,BoxError};#[actix_rt::main]asyncfn main()-> Result<(),BoxError>{// Set up our Storage
// For this example, we use the default in-memory storage mechanism
usebackground_jobs::memory_storage::{ActixTimer,Storage};letstorage=Storage::new(ActixTimer);// Configure and start our workers
letjob_queue=WorkerConfig::new(storage,move||MyState::new("My App")).register::<MyJob>().set_worker_count(DEFAULT_QUEUE,16).start();// Add our jobs
job_queue.push(MyJob::new(1,2)).await?;job_queue.push(MyJob::new(3,4)).await?;job_queue.push(MyJob::new(5,6)).await?;// Block on Actix
actix_rt::signal::ctrl_c().await?;Ok(())}
Complete Example

For the complete example project, see the examples folder

Bringing your own server/worker implementation

If you want to create your own jobs processor based on this idea, you can depend on the background-jobs-core crate, which provides the Job trait, as well as some other useful types for implementing a jobs processor and job store.

Contributing

Feel free to open issues for anything you find an issue with. Please note that any contributed code will be licensed under the AGPLv3.

License

Copyright © 2022 Riley Trautman

background-jobs is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

background-jobs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. This file is part of background-jobs.

You should have received a copy of the GNU General Public License along with background-jobs. If not, see http://www.gnu.org/licenses/.