background-jobs/examples/actix-example/src/main.rs

153 lines
4.1 KiB
Rust
Raw Normal View History

2021-10-29 19:56:53 +00:00
use actix_rt::Arbiter;
2020-03-21 02:31:03 +00:00
use anyhow::Error;
2021-11-17 17:29:53 +00:00
use background_jobs::{create_server_in_arbiter, ActixJob, MaxRetries, WorkerConfig};
2021-02-04 18:40:39 +00:00
use background_jobs_sled_storage::Storage;
use chrono::{Duration, Utc};
2021-11-17 18:33:24 +00:00
use std::{
future::{ready, Future, Ready},
pin::Pin,
};
2019-05-25 21:15:09 +00:00
2020-04-25 22:12:43 +00:00
const DEFAULT_QUEUE: &str = "default";
2019-05-25 21:15:09 +00:00
#[derive(Clone, Debug)]
pub struct MyState {
pub app_name: String,
}
2020-03-21 02:31:03 +00:00
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
2019-05-25 21:15:09 +00:00
pub struct MyJob {
some_usize: usize,
other_usize: usize,
}
2021-09-13 22:40:49 +00:00
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct PanickingJob;
2021-11-17 18:33:24 +00:00
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct LongJob;
2020-03-21 02:31:03 +00:00
#[actix_rt::main]
async fn main() -> Result<(), Error> {
2021-09-13 22:40:49 +00:00
if std::env::var_os("RUST_LOG").is_none() {
std::env::set_var("RUST_LOG", "info");
}
2020-03-21 02:31:03 +00:00
env_logger::init();
2019-05-28 00:01:21 +00:00
// Set up our Storage
2021-02-04 18:40:39 +00:00
let db = sled::Config::new().temporary(true).open()?;
let storage = Storage::new(db)?;
2019-05-25 21:15:09 +00:00
2021-10-29 19:56:53 +00:00
let arbiter = Arbiter::new();
2019-05-28 00:01:21 +00:00
// Start the application server. This guards access to to the jobs store
2021-10-29 19:56:53 +00:00
let queue_handle = create_server_in_arbiter(&arbiter, storage);
2019-05-28 00:01:21 +00:00
// Configure and start our workers
2019-05-27 17:29:11 +00:00
WorkerConfig::new(move || MyState::new("My App"))
2021-11-17 18:33:24 +00:00
.register::<LongJob>()
2021-09-13 22:40:49 +00:00
.register::<PanickingJob>()
2020-04-21 00:30:56 +00:00
.register::<MyJob>()
.set_worker_count(DEFAULT_QUEUE, 16)
2021-10-29 19:56:53 +00:00
.start_in_arbiter(&arbiter, queue_handle.clone());
2019-05-25 21:15:09 +00:00
2021-09-13 22:40:49 +00:00
// Queue some panicking job
for _ in 0..32 {
queue_handle.queue(PanickingJob)?;
}
2019-05-28 00:01:21 +00:00
// Queue our jobs
queue_handle.queue(MyJob::new(1, 2))?;
queue_handle.queue(MyJob::new(3, 4))?;
queue_handle.queue(MyJob::new(5, 6))?;
2021-02-04 18:40:39 +00:00
queue_handle.schedule(MyJob::new(7, 8), Utc::now() + Duration::seconds(2))?;
2021-11-17 18:33:24 +00:00
queue_handle.queue(LongJob)?;
2019-05-25 21:15:09 +00:00
2019-05-28 00:01:21 +00:00
// Block on Actix
2020-03-21 02:31:03 +00:00
actix_rt::signal::ctrl_c().await?;
2021-10-29 19:56:53 +00:00
arbiter.stop();
let _ = arbiter.join();
2019-05-25 21:15:09 +00:00
Ok(())
}
impl MyState {
pub fn new(app_name: &str) -> Self {
MyState {
app_name: app_name.to_owned(),
}
}
}
impl MyJob {
pub fn new(some_usize: usize, other_usize: usize) -> Self {
MyJob {
some_usize,
other_usize,
}
}
}
2020-03-21 02:31:03 +00:00
#[async_trait::async_trait]
2021-11-17 17:29:53 +00:00
impl ActixJob for MyJob {
2019-05-28 00:01:21 +00:00
type State = MyState;
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
2019-05-25 21:15:09 +00:00
// registered.
2020-04-21 00:30:56 +00:00
const NAME: &'static str = "MyJob";
2019-05-25 21:15:09 +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
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);
2020-04-21 00:30:56 +00:00
fn run(self, state: MyState) -> Self::Future {
println!("{}: args, {:?}", state.app_name, self);
2021-02-04 18:40:39 +00:00
ready(Ok(()))
2020-04-21 00:30:56 +00:00
}
2019-05-25 21:15:09 +00:00
}
2021-09-13 22:40:49 +00:00
2021-11-17 18:33:24 +00:00
#[async_trait::async_trait]
impl ActixJob for LongJob {
type State = MyState;
type Future = Pin<Box<dyn Future<Output = Result<(), Error>>>>;
const NAME: &'static str = "LongJob";
const QUEUE: &'static str = DEFAULT_QUEUE;
const MAX_RETRIES: MaxRetries = MaxRetries::Count(0);
fn run(self, _: MyState) -> Self::Future {
Box::pin(async move {
actix_rt::time::sleep(std::time::Duration::from_secs(120)).await;
Ok(())
})
}
}
2021-09-13 22:40:49 +00:00
#[async_trait::async_trait]
2021-11-17 17:29:53 +00:00
impl ActixJob for PanickingJob {
2021-09-13 22:40:49 +00:00
type State = MyState;
type Future = Ready<Result<(), Error>>;
const NAME: &'static str = "PanickingJob";
const QUEUE: &'static str = DEFAULT_QUEUE;
const MAX_RETRIES: MaxRetries = MaxRetries::Count(0);
fn run(self, _: MyState) -> Self::Future {
panic!("A panicking job does not stop others from running")
}
}