Skip to content

Getting Started

Nathan Jaremko edited this page Apr 30, 2023 · 6 revisions

1. Go make a cargo project

cargo new cwab-example

2. Navigate into that directory

cd cwab-example

3. Setup your dependencies

Open into Cargo.toml and add the follow dependencies:

anyhow = "^1.0.70"
async-trait = "^0.1.0"
cwab = "^0.5"
serde = { version = "1.0.109", features = ["derive"] }
serde_json = "^1.0.96"
tokio = { version = "1.24.2", features = ["full"] }

4. Write your simple worker

Open src/main.rs and put this in it:

use anyhow::Result;
use async_trait::async_trait;
use cwab::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
pub struct HelloJob;

#[async_trait]
impl Job for HelloJob {
    fn name(&self) -> &'static str {
        "HelloJob"
    }

    async fn perform(&self, input: Option<String>) -> Result<Option<String>, anyhow::Error> {
        let to_print = if let Some(i) = input {
            format!("Hello {}", i)
        } else {
            format!("Hello World")
        };
        println!("{}", to_print);
        Ok(None)
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    let config = Config::new(None)?;
    let cwab = Cwab::new(&config)?;
    let mut worker = cwab.worker();
    worker.register(HelloJob);

    cwab.perform_async(HelloJob, None).await?;
    cwab.perform_async(HelloJob, Some("Bob".to_string()))
        .await?;

    worker.start_working().await?;
    Ok(())
}

5. Install the cwab CLI

cargo install cwab

6. Start your worker

cargo run

7. Open a new terminal and start the librarian

You should only have one librarian running per worker cluster. This does bookkeeping tasks, like retrying failed jobs, cleaning up old dead jobs, enqueuing scheduled jobs, etc.

cwab librarian start