Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Task Laravel Package

milestone/task

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require milestone/task
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Milestone\Task\TaskServiceProvider::class,
    ],
    
  2. Publish Config:

    php artisan vendor:publish --provider="Milestone\Task\TaskServiceProvider" --tag="config"
    

    Review config/task.php for default settings (e.g., default_driver, queue_connection).

  3. First Use Case: Define a task in a controller or command:

    use Milestone\Task\Task;
    
    public function createTask()
    {
        $task = Task::create([
            'name' => 'Process user uploads',
            'payload' => ['user_id' => 123],
            'timeout' => 3600, // 1 hour
        ]);
        return $task->id;
    }
    
  4. Run the Task:

    php artisan task:run
    

    (Check config/task.php for command settings.)


Implementation Patterns

Core Workflows

  1. Task Creation:

    • Use Task::create() or Task::dispatch() (if queue-based).
    • Attach metadata via payload (serialized to JSON):
      $task = Task::create([
          'name' => 'Send email',
          'payload' => ['template' => 'welcome', 'user_id' => 42],
          'delay' => 60, // Run after 60 seconds
      ]);
      
  2. Queue Integration:

    • Configure queue_connection in config/task.php (e.g., database, redis).
    • Listen for tasks via the TaskListener facade:
      use Milestone\Task\TaskListener;
      
      TaskListener::listen(function ($task) {
          // Handle task logic here
          return ['status' => 'completed'];
      });
      
  3. Retry Logic:

    • Set max_attempts and backoff (exponential) in task config:
      $task = Task::create([
          'name' => 'Retryable job',
          'payload' => [...],
          'max_attempts' => 3,
          'backoff' => 1000, // 1 second initial delay
      ]);
      
  4. Task Chaining:

    • Use Task::chain() to link tasks sequentially:
      $task1 = Task::create(['name' => 'Step 1']);
      $task2 = Task::create(['name' => 'Step 2']);
      Task::chain($task1->id, $task2->id);
      

Integration Tips

  • Laravel Events: Bind to task.created, task.failed, or task.completed:

    event(new TaskCreated($task));
    
  • Database Schema: Extend the tasks table via migrations (e.g., add priority column):

    Schema::table('tasks', function (Blueprint $table) {
        $table->integer('priority')->default(5);
    });
    
  • Testing: Mock the TaskListener in PHPUnit:

    $this->mock(TaskListener::class)->shouldReceive('listen')->once();
    

Gotchas and Tips

Pitfalls

  1. Queue Stuck Tasks:

    • If php artisan task:run hangs, check for deadlocks in the queue table.
    • Fix: Truncate the failed_jobs table and restart the queue worker.
  2. Payload Serialization:

    • Non-serializable objects (e.g., closures) in payload will fail silently.
    • Fix: Use json_encode()-compatible data or implement __serialize().
  3. Missing Config:

    • Forgetting to publish the config may lead to TaskServiceProvider errors.
    • Fix: Run php artisan vendor:publish --tag=config after install.
  4. Timeouts:

    • Tasks with timeout set to 0 will run indefinitely.
    • Fix: Always define a realistic timeout (e.g., 3600 for 1 hour).

Debugging

  • Log Tasks: Enable debug in config/task.php to log task lifecycle events to storage/logs/task.log.

  • Inspect Queue: Use php artisan task:list to view pending tasks and their status.

  • Failed Tasks: Check the failed_jobs table for errors. Reprocess with:

    php artisan task:retry <task_id>
    

Extension Points

  1. Custom Drivers: Override the default queue driver by implementing Milestone\Task\Contracts\TaskDriver.

  2. Task Events: Extend core events (e.g., TaskFailed) in app/Providers/EventServiceProvider:

    protected $listen = [
        'Milestone\Task\Events\TaskFailed' => [
            'App\Listeners\LogFailedTask',
        ],
    ];
    
  3. Middleware: Add middleware to tasks via the middleware config array:

    'middleware' => [
        \App\Http\Middleware\Authenticate::class,
    ],
    
  4. API Endpoints: Expose task management via routes (e.g., /tasks/{id}/retry):

    Route::post('/tasks/{id}/retry', [TaskController::class, 'retry']);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver