Skip to Content

gofasta g task

Generates an async task handler file for processing work asynchronously using hibiken/asynq . Tasks are useful for offloading work from the HTTP request/response cycle, such as sending emails, processing uploads, or triggering external API calls.

Usage

gofasta g task <Name>

This command has no flags.

Examples

Generate a task for cleaning expired sessions:

gofasta g task CleanExpiredSessions

Generate a task for sending notifications:

gofasta g task SendNotification

What It Generates

Running gofasta g task CleanExpiredSessions creates one file:

app/tasks/clean_expired_sessions.go

Generated Code

// app/tasks/clean_expired_sessions.go package tasks import ( "context" "encoding/json" "github.com/hibiken/asynq" ) const TypeCleanExpiredSessions = "clean_expired_sessions" // CleanExpiredSessionsPayload contains the data needed to execute this task. type CleanExpiredSessionsPayload struct { // TODO: Add payload fields here } // HandleCleanExpiredSessions processes the CleanExpiredSessions task. func HandleCleanExpiredSessions(ctx context.Context, t *asynq.Task) error { var payload CleanExpiredSessionsPayload if err := json.Unmarshal(t.Payload(), &payload); err != nil { return err } // TODO: Implement task logic here return nil } // EnqueueCleanExpiredSessions creates and enqueues a CleanExpiredSessions task. func EnqueueCleanExpiredSessions(client *asynq.Client, payload CleanExpiredSessionsPayload) (*asynq.TaskInfo, error) { data, err := json.Marshal(payload) if err != nil { return nil, err } task := asynq.NewTask(TypeCleanExpiredSessions, data) return client.Enqueue(task) }

Task vs Job

FeatureTaskJob
Libraryhibiken/asynqscheduler.Job interface
TriggerEnqueued from code (manual)Cron schedule (automatic)
PayloadCarries a custom payloadNone (runs with context only)
Use caseEvent-driven async processingPeriodic maintenance
PatternHandle function + Enqueue helperName() + Run() methods

Enqueuing Tasks

To enqueue a task from a service or controller:

func (s *UserServiceImpl) Register(req dtos.RegisterRequest) (*dtos.UserResponse, error) { user, err := s.repo.Create(mapToUser(req)) if err != nil { return nil, err } // Enqueue the async task _, err = tasks.EnqueueCleanExpiredSessions(s.asynqClient, tasks.CleanExpiredSessionsPayload{ // populate fields }) if err != nil { slog.Error("failed to enqueue task", "error", err) } return dtos.ToUserResponse(user), nil }
Last updated on