To define a job, create an asynchronous function and decorate it with the #[job] attribute.
Function Signature Requirements:
- The first argument must always be a
CurrentJob instance. - Subsequent arguments are optional and can be used to access context provided via
JobRegistry::set_context. - The function must return a
Result<(), Box<dyn Error + Send + Sync + 'static>>.
Key Operations within a Job:
- Payload Decoding: Use
current_job.json()? to decode a JSON payload into a type that implements Deserialize. - Completion: Call
current_job.complete().await? to mark the job as successfully finished.
Configuration:
Use the #[job] attribute to set default options, such as channel_name.
use std::error::Error;
use sqlxmq::{job, CurrentJob};
// Arguments to the `#[job]` attribute allow setting default job options.
#[job(channel_name = "foo")]
async fn example_job(
// The first argument should always be the current job.
mut current_job: CurrentJob,
// Additional arguments are optional, but can be used to access context
// provided via [`JobRegistry::set_context`].
message: &'static str,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
// Decode a JSON payload
let who: Option<String> = current_job.json()?;
// Do some work
println!("{}, {}!", message, who.as_deref().unwrap_or("world"));
// Mark the job as complete
current_job.complete().await?;
Ok(())
}