2018-11-18 01:39:04 +00:00
|
|
|
# Background Jobs
|
2018-06-29 00:01:34 +00:00
|
|
|
|
2018-11-18 01:39:04 +00:00
|
|
|
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.
|
|
|
|
|
2019-07-30 22:30:08 +00:00
|
|
|
- [Read the documentation on docs.rs](https://docs.rs/background-jobs)
|
|
|
|
- [Find the crate on crates.io](https://crates.io/crates/background-jobs)
|
2020-04-21 00:30:56 +00:00
|
|
|
- [Hit me up on Mastodon](https://asonix.dog/@asonix)
|
2019-07-30 22:30:08 +00:00
|
|
|
|
2018-11-18 01:39:04 +00:00
|
|
|
### Usage
|
|
|
|
#### Add Background Jobs to your project
|
|
|
|
```toml
|
|
|
|
[dependencies]
|
2021-02-03 22:32:56 +00:00
|
|
|
actix-rt = "2.0.0"
|
|
|
|
background-jobs = "0.9.0"
|
2020-04-21 00:42:39 +00:00
|
|
|
anyhow = "1.0"
|
2021-02-03 22:32:56 +00:00
|
|
|
futures = "0.3"
|
2020-04-21 00:42:39 +00:00
|
|
|
serde = { version = "1.0", features = ["derive"] }
|
2018-11-18 01:39:04 +00:00
|
|
|
```
|
|
|
|
|
|
|
|
#### 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 implment the `Job`, `serde::Serialize`, and `serde::DeserializeOwned`.
|
|
|
|
|
|
|
|
```rust
|
2019-05-25 21:15:09 +00:00
|
|
|
use background_jobs::Job;
|
2020-04-21 00:42:39 +00:00
|
|
|
use anyhow::Error;
|
|
|
|
use futures::future::{ok, Ready};
|
2019-05-25 21:15:09 +00:00
|
|
|
|
2020-04-21 00:42:39 +00:00
|
|
|
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
|
2018-11-18 01:39:04 +00:00
|
|
|
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 {
|
2019-05-28 00:01:21 +00:00
|
|
|
type State = ();
|
2020-04-21 00:42:39 +00:00
|
|
|
type Future = Ready<Result<(), Error>>;
|
2019-05-28 00:01:21 +00:00
|
|
|
|
2020-04-21 00:30:56 +00:00
|
|
|
const NAME: &'static str = "MyJob";
|
|
|
|
|
2019-09-22 17:53:06 +00:00
|
|
|
fn run(self, _: Self::State) -> Self::Future {
|
2018-11-18 01:39:04 +00:00
|
|
|
info!("args: {:?}", self);
|
|
|
|
|
2020-04-21 00:42:39 +00:00
|
|
|
ok(())
|
2018-11-18 01:39:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2018-11-18 21:05:03 +00:00
|
|
|
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.
|
|
|
|
|
2018-11-18 21:10:18 +00:00
|
|
|
```rust
|
2018-11-18 21:05:03 +00:00
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
pub struct MyState {
|
|
|
|
pub app_name: String,
|
|
|
|
}
|
|
|
|
|
2019-05-25 21:15:09 +00:00
|
|
|
impl MyState {
|
|
|
|
pub fn new(app_name: &str) -> Self {
|
|
|
|
MyState {
|
|
|
|
app_name: app_name.to_owned(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-28 00:01:21 +00:00
|
|
|
impl Job for MyJob {
|
|
|
|
type State = MyState;
|
2020-04-21 00:42:39 +00:00
|
|
|
type Future = Ready<Result<(), Error>>;
|
2019-05-28 00:01:21 +00:00
|
|
|
|
2020-04-21 00:30:56 +00:00
|
|
|
// 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
|
2018-11-18 01:39:04 +00:00
|
|
|
// registered.
|
2020-04-21 00:30:56 +00:00
|
|
|
const NAME: &'static str = "MyJob";
|
2018-11-18 01:39:04 +00:00
|
|
|
|
|
|
|
// 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
|
2018-11-18 14:43:10 +00:00
|
|
|
const QUEUE: &'static str = DEFAULT_QUEUE;
|
2018-11-18 01:39:04 +00:00
|
|
|
|
|
|
|
// The number of times background-jobs should try to retry a job before giving up
|
|
|
|
//
|
|
|
|
// Jobs can optionally override this value
|
2018-11-18 14:43:10 +00:00
|
|
|
const MAX_RETRIES: MaxRetries = MaxRetries::Count(1);
|
2018-11-18 01:39:04 +00:00
|
|
|
|
|
|
|
// The logic to determine how often to retry this job if it fails
|
|
|
|
//
|
|
|
|
// Jobs can optionally override this value
|
2020-04-21 00:30:56 +00:00
|
|
|
const BACKOFF: Backoff = Backoff::Exponential(2);
|
|
|
|
|
|
|
|
fn run(self, state: Self::State) -> Self::Future {
|
|
|
|
info!("{}: args, {:?}", state.app_name, self);
|
|
|
|
|
2020-04-21 00:42:39 +00:00
|
|
|
ok(())
|
2020-04-21 00:30:56 +00:00
|
|
|
}
|
2018-11-18 01:39:04 +00:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
#### Running jobs
|
2019-05-25 21:15:09 +00:00
|
|
|
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
|
2018-11-18 01:39:04 +00:00
|
|
|
spawning new jobs.
|
|
|
|
|
2019-05-25 21:15:09 +00:00
|
|
|
`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`,
|
2020-04-21 00:42:39 +00:00
|
|
|
or the provided in-memory store can be used.
|
2018-11-18 14:43:10 +00:00
|
|
|
|
|
|
|
With that out of the way, back to the examples:
|
|
|
|
|
2019-05-25 21:15:09 +00:00
|
|
|
##### Main
|
2018-11-18 01:39:04 +00:00
|
|
|
```rust
|
2020-04-21 00:42:39 +00:00
|
|
|
use background_jobs::{create_server, WorkerConfig};
|
|
|
|
use anyhow::Error;
|
2018-11-18 01:39:04 +00:00
|
|
|
|
2020-04-21 00:30:56 +00:00
|
|
|
#[actix_rt::main]
|
|
|
|
async fn main() -> Result<(), Error> {
|
|
|
|
env_logger::init();
|
2019-05-25 21:15:09 +00:00
|
|
|
// Set up our Storage
|
2019-05-28 00:01:21 +00:00
|
|
|
// For this example, we use the default in-memory storage mechanism
|
|
|
|
use background_jobs::memory_storage::Storage;
|
|
|
|
let storage = Storage::new();
|
|
|
|
|
2019-05-25 21:15:09 +00:00
|
|
|
// Start the application server. This guards access to to the jobs store
|
2020-04-21 00:30:56 +00:00
|
|
|
let queue_handle = create_server(storage);
|
2018-11-18 01:39:04 +00:00
|
|
|
|
2019-05-25 21:15:09 +00:00
|
|
|
// Configure and start our workers
|
2019-05-28 00:01:21 +00:00
|
|
|
WorkerConfig::new(move || MyState::new("My App"))
|
2020-04-21 00:30:56 +00:00
|
|
|
.register::<MyJob>()
|
|
|
|
.set_worker_count(DEFAULT_QUEUE, 16)
|
2019-05-28 00:01:21 +00:00
|
|
|
.start(queue_handle.clone());
|
2018-11-18 01:39:04 +00:00
|
|
|
|
2019-05-25 21:15:09 +00:00
|
|
|
// Queue our jobs
|
2019-05-28 00:01:21 +00:00
|
|
|
queue_handle.queue(MyJob::new(1, 2))?;
|
|
|
|
queue_handle.queue(MyJob::new(3, 4))?;
|
|
|
|
queue_handle.queue(MyJob::new(5, 6))?;
|
2018-11-18 01:39:04 +00:00
|
|
|
|
2019-05-25 21:15:09 +00:00
|
|
|
// Block on Actix
|
2020-04-21 00:30:56 +00:00
|
|
|
actix_rt::signal::ctrl_c().await?;
|
2018-11-18 01:39:04 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
```
|
2018-11-18 14:43:10 +00:00
|
|
|
|
|
|
|
##### Complete Example
|
2019-05-25 21:15:09 +00:00
|
|
|
For the complete example project, see [the examples folder](https://git.asonix.dog/Aardwolf/background-jobs/src/branch/master/examples/actix-example)
|
2018-12-16 19:44:25 +00:00
|
|
|
|
|
|
|
#### Bringing your own server/worker implementation
|
2018-11-18 01:39:04 +00:00
|
|
|
If you want to create your own jobs processor based on this idea, you can depend on the
|
2020-04-21 00:30:56 +00:00
|
|
|
`background-jobs-core` crate, which provides the Job trait, as well as some
|
2019-05-25 21:15:09 +00:00
|
|
|
other useful types for implementing a jobs processor and job store.
|
2018-11-18 01:39:04 +00:00
|
|
|
|
|
|
|
### Contributing
|
|
|
|
Feel free to open issues for anything you find an issue with. Please note that any contributed code will be licensed under the GPLv3.
|
|
|
|
|
|
|
|
### License
|
2019-09-15 20:51:33 +00:00
|
|
|
This work is licensed under the Cooperative Software License. This is not a Free Software
|
|
|
|
License, but may be considered a "source-available License." For most hobbyists, self-employed
|
|
|
|
developers, worker-owned companies, and cooperatives, this software can be used in most
|
|
|
|
projects so long as this software is distributed under the terms of the CSL. For more
|
|
|
|
information, see the provided LICENSE file. If none exists, the license can be found online
|
|
|
|
[here](https://lynnesbian.space/csl/). If you are a free software project and wish to use this
|
|
|
|
software under the terms of the GNU Affero General Public License, please contact me at
|
|
|
|
[asonix@asonix.dog](mailto:asonix@asonix.dog) and we can sort that out. If you wish to use this
|
|
|
|
project under any other license, especially in proprietary software, the answer is likely no.
|