Skip to content

Jobs ​

A Job is a named unit of queued work with a payload and a registered handler.

Jobs make background work explicit, observable, and operable. Retry policy is opt-in: a generated job does not gain application retries until dispatch sets a retry budget.

For a complete local exercise with a saved record, see Run a Photo Job.

When to Use Jobs ​

Use a job when background work needs a stable name, typed payload, handler, retry behavior, or worker lifecycle. Start with a small payload containing IDs that let the handler load current source-of-truth data.

A direct function call is simpler for synchronous behavior. Publish an event instead when the message is a fact that subscribers may observe. Add dedicated queues, retry policy, idempotency keys, and worker allocation when the operational requirements call for them.

Generate a Job ​

From an app with queue support, generate a report job on the default queue:

bash
forj make:job reports:generate

This creates internal/reports/generate_job.go and adds the constructor and handler registration to app/wire/inject_jobs_app.go. For an additional app, use forj admin make:job reports:generate; its registration lives in app/admin/wire/inject_jobs_app.go.

The generated payload is empty, Queue accepts that payload type, and HandleTask only decodes it. Generation alone does not implement report generation. The Make Command Reference shows the complete scaffold, queue selection, and removal options. Naming Conventions explains names such as reports:generate.

Implement the Job ​

The following fragments modify internal/reports/generate_job.go. They assume your report service has Generate(context.Context, string) error, which loads the report's current state and writes its output. Keep that behavior in the service and test it directly.

Keep GenerateJobTypeName as "reports:generate": registration and transport use this stable identifier. The generated Queue signature stays typed while the payload gains a report ID.

Payload and Dependencies ​

go
// GenerateJobPayload identifies the report whose current state the worker should load.
type GenerateJobPayload struct {
	ReportID string `json:"report_id"`
}

// reportGenerator lets handler tests replace report generation with a recording fake.
type reportGenerator interface {
	Generate(context.Context, string) error
}

// GenerateJob dispatches reports and delegates their generation to the service.
type GenerateJob struct {
	queues  *queues.Manager
	service reportGenerator
}

// NewGenerateJob constructs the job with its queue manager and report service.
func NewGenerateJob(queues *queues.Manager, service *Service) *GenerateJob {
	return &GenerateJob{queues: queues, service: service}
}

Add reports.NewService and its dependencies to app/wire/inject_services_app.go. Keep the generated job provider and handler registration. Application Services covers service ownership.

Carry IDs for mutable records so workers load current state. A bounded batch of IDs or compact immutable snapshot can avoid extra reads when throughput requires it. Avoid queueing persistence models, which couple payloads to database structure and can carry stale state.

Dispatch ​

Jobs own their dispatch shape. Add time to the file's imports when applying this policy:

go
// Queue dispatches report generation with its retry and timeout policy.
func (j *GenerateJob) Queue(ctx context.Context, payload GenerateJobPayload) error {
	data, err := json.Marshal(payload)
	if err != nil {
		return err
	}

	_, err = j.queues.WithContext(ctx).Dispatch(
		queue.NewJob(GenerateJobTypeName).
			Payload(data).
			OnQueue("default").
			Retry(3).
			Backoff(2*time.Second).
			Timeout(30*time.Second),
	)
	return err
}

When the HTTP request hands work to the local worker, detach the request cancellation before calling the injected job. The worker has its own timeout for the job.

go
dispatchCtx := context.WithoutCancel(ctx)
err := generateJob.Queue(dispatchCtx, reports.GenerateJobPayload{ReportID: "report-42"})

Here, ctx is the request's context.Context. Import context at the call site. Inside the reports package, omit the reports. qualifier. Keep the producer separate from the report service called by the job to avoid a constructor cycle. Use a named queue only when reports need their own concurrency or backend.

Retry(3) permits up to three application retry attempts after the first attempt. Backoff delays those retries. With workerpool, Timeout bounds the job run, including retries and their delays. Set these values to fit the work and the service-level objective.

Handling ​

Handlers bind payloads and delegate business behavior:

go
// HandleTask delegates the queued report reference to the report service.
func (j *GenerateJob) HandleTask(ctx context.Context, msg queue.Message) error {
	var payload GenerateJobPayload
	if err := msg.Bind(&payload); err != nil {
		return fmt.Errorf("bind generate report payload: %w", err)
	}

	return j.service.Generate(ctx, payload.ReportID)
}

Return errors for retryable failures so the queue can apply the dispatch policy. Return queue.Permanent(err) for a terminal failure, such as a report that no longer exists, to stop spending the remaining application retry budget. Define that distinction in the report service's error contract.

Broker redelivery after an infrastructure failure is distinct from the application retry budget. Review acknowledgement and durability behavior for the selected driver, and keep handlers idempotent even when Retry(0) is intentional.

Test Dispatch and Handling ​

Keep dispatch and handling as separate assertions.

For dispatch, use a recording queue backend and assert the job type, logical queue, payload ID, retry budget, backoff, and timeout. For handling, use a local sync runtime to construct the delivered message. Put this test in internal/reports/generate_job_test.go:

go
package reports

import (
	"context"
	"testing"

	"github.com/goforj/queue"
)

// recordingGenerator records which report the handler delegates to the service.
type recordingGenerator struct {
	reportID string
}

// Generate records the report reference without writing a real report.
func (g *recordingGenerator) Generate(_ context.Context, reportID string) error {
	g.reportID = reportID
	return nil
}

// TestGenerateJobHandlesReport verifies decoding and service delegation through a local runtime.
func TestGenerateJobHandlesReport(t *testing.T) {
	generator := &recordingGenerator{}
	job := &GenerateJob{service: generator}
	runtime, err := queue.New(queue.Config{Driver: queue.DriverSync})
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { _ = runtime.Shutdown(context.Background()) })
	runtime.Register(GenerateJobTypeName, job.HandleTask)
	if err := runtime.StartWorkers(context.Background()); err != nil {
		t.Fatal(err)
	}
	_, err = runtime.Dispatch(queue.NewJob(GenerateJobTypeName).
		Payload(GenerateJobPayload{ReportID: "report-42"}))
	if err != nil {
		t.Fatal(err)
	}
	if generator.reportID != "report-42" {
		t.Fatalf("report ID = %q, want report-42", generator.reportID)
	}
}

Run it from the app root:

bash
go test ./internal/reports -run TestGenerateJobHandlesReport

Expected result: the package reports ok. This proves payload decoding and delegation. Add malformed-payload, dependency-error, terminal-error, and repeated-delivery cases. Test the real service separately for output and idempotency.

Use a smoke test through the generated manager and a worker to verify handler registration and delivery. With workerpool, use the combined App. Separate producer and worker processes require a shared driver. In deployment, use the Queue Workers runbook to verify the job name and outcome.

Existing Job Registration ​

The generated job reference shows the registration path for new jobs. The App-owned registerJobHandlers function is also the extension point for a manually written job.

Projects created before this registration seam may already contain custom job constructors that were never registered. Rerender migrates known framework jobs but does not guess whether an arbitrary provider is a job. Add each older custom job as a typed registerJobHandlers parameter and register its type name with queueManager.Register; future make:job calls maintain both entries automatically.

Do not register handlers after workers are already running.

Next Steps ​