VOOZH about

URL: https://deepwiki.com/hypervel/queue/6.1-work-command

⇱ Work Command | hypervel/queue | DeepWiki


Loading...
Menu

Work Command

Overview

The WorkCommand class implements the queue:work console command, which is the primary interface for processing queued jobs in the Hypervel Queue system. This command starts a worker process that continuously fetches and executes jobs from specified queue connections.

The command operates in two modes: daemon mode (continuous processing) and once mode (single job execution). It provides extensive configuration options for controlling worker behavior, resource limits, concurrency, and output formatting.

For information about the underlying worker execution logic, see Worker Class. For worker configuration parameters, see Worker Options and Configuration.

Sources: src/Console/WorkCommand.php29-343


Command Signature

The command is invoked as queue:work with the following signature:

queue:work {connection?} [options]

Arguments

ArgumentDescriptionDefault
connectionThe name of the queue connection to workqueue.default config value

Options

OptionTypeDescriptionDefault
--namestringThe name of the workerdefault
--queuestringThe names of the queues to work (comma-separated)Connection's default queue
--daemonbooleanRun the worker in daemon mode (Deprecated)false
--oncebooleanOnly process the next job on the queuefalse
--concurrencyintegerThe number of jobs to process at once1
--stop-when-emptybooleanStop when the queue is emptyfalse
--delayintegerThe number of seconds to delay failed jobs (Deprecated)0
--backoffintegerThe number of seconds to wait before retrying a job that encountered an uncaught exception0
--max-jobsintegerThe number of jobs to process before stopping0 (unlimited)
--max-timeintegerThe maximum number of seconds the worker should run0 (unlimited)
--forcebooleanForce the worker to run even in maintenance modefalse
--memoryintegerThe memory limit in megabytes128
--sleepintegerNumber of seconds to sleep when no job is available3
--restintegerNumber of seconds to rest between jobs0
--timeoutintegerThe number of seconds a child process can run60
--monitor-intervalintegerThe time interval of seconds for monitoring timeout jobs1
--triesintegerNumber of times to attempt a job before logging it failed1
--jsonbooleanOutput the queue worker information as JSONfalse

Sources: src/Console/WorkCommand.php37-56


Command Execution Flow

The command execution follows a structured flow from initialization through worker invocation:


Sources: src/Console/WorkCommand.php88-128


Worker Options Assembly

The gatherWorkerOptions() method collects all command-line options and configuration values into a WorkerOptions object:


The method handles a special case for the --backoff option: it uses the maximum value between --backoff and the deprecated --delay option for backward compatibility.

Sources: src/Console/WorkCommand.php133-156


Event Listening System

The command registers event listeners to monitor job processing lifecycle events and provide real-time feedback:


The event listeners are registered only once using a static flag $hasRegisteredListeners to prevent duplicate registration across multiple command invocations.

Sources: src/Console/WorkCommand.php161-187


Output Formats

CLI Output Mode

In CLI mode (default), the command displays formatted output with visual indicators:

2024-01-15 10:30:45 App\Jobs\ProcessPodcast ........................... RUNNING
2024-01-15 10:30:45 App\Jobs\ProcessPodcast ....................... 150ms DONE

The output includes:

  • Timestamp (formatted according to queue.output_timezone or app.timezone config)
  • Job name resolved via $job->resolveName()
  • Job ID (only in verbose mode: -v)
  • Dots to fill terminal width
  • Runtime duration
  • Status: RUNNING (yellow), DONE (green), or FAIL (red/yellow)

Key Implementation Details:

FeatureMethodDescription
Timestampnow()Returns Carbon instance with timezone from config
RuntimerunTimeForHumans()Calculates duration since latestStartedAt
Terminal widthTerminal::hasSttyAvailable()Checks if terminal supports width detection
Dot calculationDynamicmax(terminal()->width() - [lengths] - 33, 0)

Sources: src/Console/WorkCommand.php207-246 src/Console/WorkCommand.php286-297

JSON Output Mode

When the --json flag is used, the command outputs structured JSON logs for each job event:


For completion events, a duration field is added:


JSON Output Fields:

FieldDescriptionValues
levelLog levelinfo (starting/success) or warning (failure)
idJob ID from queueString
uuidJob UUIDString
connectionQueue connection nameString
queueQueue nameString
jobResolved job class nameString
statusCurrent statusstarting, success, failed, released_after_exception
resultFinal job statedeleted, released, failed, or empty
attemptsNumber of attemptsInteger
exceptionException class (if any)String
messageException message (if any)String
timestampISO 8601 timestampString
durationExecution time in secondsFloat (completion events only)

Sources: src/Console/WorkCommand.php252-281


Queue Selection and Configuration

Connection Resolution

The command resolves the queue connection in the following order:

  1. Command argument: queue:work redis
  2. Default configuration: queue.default in config/queue.php

Sources: src/Console/WorkCommand.php95-96 src/Console/WorkCommand.php316-322

Multiple Queue Support

The --queue option accepts comma-separated queue names:


The worker will process jobs from these queues in priority order (left to right).

Sources: src/Console/WorkCommand.php40 src/Console/WorkCommand.php316-322


Failed Job Logging

When a JobFailed event is dispatched, the command automatically logs the failure to the FailedJobProviderInterface:


The logged information includes:

  • Connection name
  • Queue name
  • Raw job payload (for retry purposes)
  • Exception details

Sources: src/Console/WorkCommand.php180-184 src/Console/WorkCommand.php302-311


Execution Modes

Daemon Mode

By default (or when --daemon flag is used), the command runs the worker in daemon mode via $worker->daemon(). This mode:

  • Continuously processes jobs in an infinite loop
  • Monitors resource usage (memory, time, job count)
  • Supports concurrent job processing via coroutines
  • Handles graceful shutdown signals

Example:


Once Mode

When the --once flag is provided, the command processes a single job via $worker->runNextJob() and then exits:


This mode is useful for:

  • Testing job processing
  • Running in cron jobs
  • Serverless environments
  • Debugging individual jobs

Sources: src/Console/WorkCommand.php118-128


Component Integration

The WorkCommand integrates with multiple core components through dependency injection:


Injected Dependencies:

DependencyUsage
ContainerInterfaceResolves EventDispatcherInterface and FailedJobProviderInterface
ConfigInterfaceReads queue configuration, connection settings, timezone
WorkerExecutes job processing logic
CacheFactoryProvides cache for worker restart signal coordination

Sources: src/Console/WorkCommand.php76-83 src/Console/WorkCommand.php120-122


Configuration Values Referenced

The command reads the following configuration values:

Configuration KeyPurposeDefault
queue.defaultDefault connection nameN/A
queue.connections.{connection}.queueDefault queue for connectiondefault
queue.concurrency_numberGlobal concurrency setting1
queue.output_timezoneTimezone for output timestampsapp.timezone
app.timezoneApplication timezoneN/A

Sources: src/Console/WorkCommand.php95-96 src/Console/WorkCommand.php135-139 src/Console/WorkCommand.php288-294 src/Console/WorkCommand.php318-321


State Management

The command maintains minimal state to track job execution timing:

PropertyTypePurpose
$latestStartedAt?floatMicrotime when the last job started processing
$hasRegisteredListenersstatic boolFlag to prevent duplicate event listener registration

The flushState() static method resets the $hasRegisteredListeners flag, primarily used for testing purposes.

Sources: src/Console/WorkCommand.php66-71 src/Console/WorkCommand.php219 src/Console/WorkCommand.php275 src/Console/WorkCommand.php339-342