Skip to content

hummingbird-project/swift-jobs

Repository files navigation

Jobs

Offload work from your server to other servers.

Register a Job

// create job queue stored in local memory, that can run four jobs concurrently
let jobQueue = JobQueue(
    .memory, 
    numWorkers: 4, 
    logger: logger
)
// Define email job parameters. Its job name has to be unique
struct SendEmailJobParameters: JobParameters {
    static let jobName = "SendEmail"
    let to: String
    let subject: String
    let body: String
}
// Register jobs with job queue
jobQueue.registerJob(parameters: SendEmailJobParameters.self) { parameters, context in
    try await myEmailService.sendEmail(
        to: parameters.to, 
        subject: parameters.subject, 
        body: parameters.body
    )
}
// Push instance of job onto queue
jobQueue.push(SendEmailJobParameters(
    to: "Ellen", 
    subject:"Hello", 
    body: "Hi there!"
))

Process Jobs

JobQueue conforms to Service and can be used with ServiceGroup from ServiceLifecycle.

let serviceGroup = ServiceGroup(
    configuration: .init(
        services: [jobQueue],
        gracefulShutdownSignals: [.sigterm, .sigint],
        logger: Logger(label: "JobQueueService")
    )
)
try await serviceGroup.run()

Or it can be added as a service attached to a Hummingbird application

let app = Application(router: router, services: [jobQueue])

When the JobQueue service is running it processes jobs as they appear on the queue. The maxWorkers field in the JobQueue initializer indicates how many jobs it will run concurrently.

Documentation

You can find documentation for Jobs here. The hummingbird-examples repository has a number of examples of different uses of the library.