{"id":26420003,"url":"https://github.com/ody-dev/task","last_synced_at":"2026-02-23T21:44:36.129Z","repository":{"id":281794697,"uuid":"946284465","full_name":"ody-dev/task","owner":"ody-dev","description":null,"archived":false,"fork":false,"pushed_at":"2025-04-06T18:31:02.000Z","size":15,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-06T19:16:56.227Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ody-dev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-03-10T22:44:45.000Z","updated_at":"2025-04-06T18:22:04.000Z","dependencies_parsed_at":"2025-03-16T20:35:23.600Z","dependency_job_id":"7e28af7b-0a68-4713-85ae-7aa892c4dc9f","html_url":"https://github.com/ody-dev/task","commit_stats":null,"previous_names":["ody-dev/ody-task","ody-dev/task"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/ody-dev/task","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ody-dev%2Ftask","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ody-dev%2Ftask/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ody-dev%2Ftask/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ody-dev%2Ftask/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ody-dev","download_url":"https://codeload.github.com/ody-dev/task/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ody-dev%2Ftask/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":259880370,"owners_count":22925926,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-03-18T02:01:01.264Z","updated_at":"2026-02-23T21:44:36.091Z","avatar_url":"https://github.com/ody-dev.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# TaskManager API Reference\n\n## Table of Contents\n\n- [Task Class](#task-class)\n- [TaskInterface](#taskinterface)\n- [TaskMiddlewareInterface](#taskmiddlewareinterface)\n- [TaskGroup Class](#taskgroup-class)\n- [TaskBatch Class](#taskbatch-class)\n- [TaskManager Class](#taskmanager-class)\n- [TaskHandler Class](#Taskhandler-class)\n\n## Task Class\n\nThe primary entry point for creating and managing tasks in the system.\n\n### Constants\n\n| Constant | Type | Value | Description |\n|----------|------|-------|-------------|\n| `PRIORITY_HIGH` | int | 20 | High priority tasks are processed before normal and low priority tasks |\n| `PRIORITY_NORMAL` | int | 10 | Default priority level |\n| `PRIORITY_LOW` | int | 5 | Low priority tasks are processed after high and normal priority tasks |\n| `STATUS_PENDING` | string | 'pending' | Task is waiting to be processed |\n| `STATUS_PROCESSING` | string | 'processing' | Task is currently being processed |\n| `STATUS_COMPLETED` | string | 'completed' | Task has been completed successfully |\n| `STATUS_FAILED` | string | 'failed' | Task has failed |\n| `STATUS_CANCELLED` | string | 'cancelled' | Task has been cancelled |\n| `STATUS_RETRYING` | string | 'retrying' | Task failed but will be retried |\n\n### Methods\n\n#### `execute(string $taskClass, array $params = [], int $priority = self::PRIORITY_NORMAL): int`\n\nExecute a task immediately.\n\n**Parameters:**\n- `$taskClass`: The full class name of the task to execute (must implement TaskInterface)\n- `$params`: Parameters to pass to the task's handle method\n- `$priority`: Priority level for the task\n\n**Returns:** Task ID\n\n**Example:**\n```php\n$taskId = Task::execute(\\App\\Tasks\\SendEmailTask::class, [\n    'to' =\u003e 'user@example.com',\n    'subject' =\u003e 'Welcome',\n    'body' =\u003e 'Welcome to our service!'\n]);\n```\n\n#### `later(string $taskClass, array $params = [], int $delayMs = 1000, int $priority = self::PRIORITY_NORMAL): int`\n\nSchedule a task to run after a delay.\n\n**Parameters:**\n- `$taskClass`: The full class name of the task to execute\n- `$params`: Parameters to pass to the task's handle method\n- `$delayMs`: Delay in milliseconds before executing the task\n- `$priority`: Priority level for the task\n\n**Returns:** Task ID\n\n**Example:**\n```php\n$taskId = Task::later(\\App\\Tasks\\SendReminderTask::class, \n    ['user_id' =\u003e 123], \n    60000  // 60 seconds\n);\n```\n\n#### `withRetry(string $taskClass, array $params = [], array $retryOptions = ['attempts' =\u003e 3, 'delay' =\u003e 1000, 'multiplier' =\u003e 2], int $priority = self::PRIORITY_NORMAL): int`\n\nExecute a task with automatic retry on failure.\n\n**Parameters:**\n- `$taskClass`: The full class name of the task to execute\n- `$params`: Parameters to pass to the task's handle method\n- `$retryOptions`: Retry configuration\n  - `attempts`: Maximum number of attempts (including the first attempt)\n  - `delay`: Initial delay in milliseconds before retrying\n  - `multiplier`: Multiplier for exponential backoff (each retry increases delay by this factor)\n- `$priority`: Priority level for the task\n\n**Returns:** Task ID\n\n**Example:**\n```php\n$taskId = Task::withRetry(\\App\\Tasks\\APIRequestTask::class, \n    ['endpoint' =\u003e '/api/data', 'method' =\u003e 'GET'], \n    ['attempts' =\u003e 5, 'delay' =\u003e 1000, 'multiplier' =\u003e 2]\n);\n```\n\n#### `group(string $name = null): TaskGroup`\n\nCreate a new task group for organizing related tasks.\n\n**Parameters:**\n- `$name`: Optional name for the group (auto-generated if not provided)\n\n**Returns:** A new TaskGroup instance\n\n**Example:**\n```php\n$group = Task::group('user-onboarding')\n    -\u003eadd(\\App\\Tasks\\CreateUserTask::class, ['email' =\u003e 'user@example.com'])\n    -\u003eadd(\\App\\Tasks\\SendWelcomeEmailTask::class, ['email' =\u003e 'user@example.com']);\n```\n\n#### `batch(array $tasks): TaskBatch`\n\nCreate a batch for processing multiple similar tasks efficiently.\n\n**Parameters:**\n- `$tasks`: Array of task definitions (strings or arrays with 'class' and 'params' keys)\n\n**Returns:** A new TaskBatch instance\n\n**Example:**\n```php\n$tasks = [];\nforeach ($users as $user) {\n    $tasks[] = [\n        'class' =\u003e \\App\\Tasks\\NotifyUserTask::class,\n        'params' =\u003e ['user_id' =\u003e $user-\u003eid, 'message' =\u003e 'System maintenance']\n    ];\n}\n$batch = Task::batch($tasks);\n```\n\n#### `cancel(int $taskId): bool`\n\nCancel a pending task.\n\n**Parameters:**\n- `$taskId`: The ID of the task to cancel\n\n**Returns:** True if the task was cancelled, false otherwise\n\n**Example:**\n```php\n$cancelled = Task::cancel($taskId);\n```\n\n#### `status(int $taskId): array`\n\nGet the current status of a task.\n\n**Parameters:**\n- `$taskId`: The ID of the task\n\n**Returns:** Array with task status information\n\n**Example:**\n```php\n$status = Task::status($taskId);\n// Returns: [\n//   'id' =\u003e 123,\n//   'class' =\u003e '\\App\\Tasks\\SendEmailTask',\n//   'status' =\u003e 'completed',\n//   'attempts' =\u003e 1,\n//   'created_at' =\u003e 1615480245.7843,\n//   'started_at' =\u003e 1615480245.8421,\n//   'completed_at' =\u003e 1615480246.0124,\n//   'execution_time' =\u003e 0.1703,\n//   'result' =\u003e [...],\n//   'error' =\u003e null\n// ]\n```\n\n## TaskInterface\n\nInterface that all task classes must implement.\n\n### Methods\n\n#### `handle(array $params = [])`\n\nProcess the task.\n\n**Parameters:**\n- `$params`: Parameters passed to the task\n\n**Returns:** Any value, which will be available in the task result\n\n**Example:**\n```php\nclass SendEmailTask implements TaskInterface\n{\n    public function handle(array $params = [])\n    {\n        // Send email logic here\n        $result = mail($params['to'], $params['subject'], $params['body']);\n        \n        return [\n            'success' =\u003e $result,\n            'to' =\u003e $params['to'],\n            'sent_at' =\u003e date('Y-m-d H:i:s')\n        ];\n    }\n}\n```\n\n## TaskMiddlewareInterface\n\nInterface for creating task middleware.\n\n### Methods\n\n#### `process(array $task): array`\n\nProcess the task before it's enqueued.\n\n**Parameters:**\n- `$task`: Array containing task information\n  - `params`: The task parameters\n\n**Returns:** Modified task array\n\n**Example:**\n```php\nclass LoggingMiddleware implements TaskMiddlewareInterface\n{\n    public function process(array $task): array\n    {\n        // Add logging metadata to the task\n        $task['params']['__meta'] = [\n            'logged_at' =\u003e time(),\n            'request_id' =\u003e $_SERVER['REQUEST_ID'] ?? uniqid()\n        ];\n        \n        return $task;\n    }\n}\n```\n\n## TaskGroup Class\n\nManages a group of related tasks.\n\n### Methods\n\n#### `__construct(?string $name = null)`\n\nCreate a new task group.\n\n**Parameters:**\n- `$name`: Optional name for the group (auto-generated if not provided)\n\n#### `add(string $taskClass, array $params = [], int $priority = Task::PRIORITY_NORMAL): self`\n\nAdd a task to the group.\n\n**Parameters:**\n- `$taskClass`: The full class name of the task to execute\n- `$params`: Parameters to pass to the task's handle method\n- `$priority`: Priority level for the task\n\n**Returns:** $this (for method chaining)\n\n#### `concurrency(?int $limit): self`\n\nSet a concurrency limit for the group.\n\n**Parameters:**\n- `$limit`: Maximum number of tasks in the group that can run simultaneously (null for no limit)\n\n**Returns:** $this (for method chaining)\n\n#### `allowFailures(bool $allow = true): self`\n\nConfigure whether failures in one task should stop other tasks in the group.\n\n**Parameters:**\n- `$allow`: If true, other tasks will continue even if some tasks fail\n\n**Returns:** $this (for method chaining)\n\n#### `middleware($middleware): self`\n\nAdd middleware to all tasks in this group.\n\n**Parameters:**\n- `$middleware`: Middleware class name or callable\n\n**Returns:** $this (for method chaining)\n\n#### `dispatch(): array`\n\nExecute all tasks in the group.\n\n**Returns:** Array of task IDs\n\n#### `wait(int $timeout = 30000): array`\n\nWait for all tasks in the group to complete.\n\n**Parameters:**\n- `$timeout`: Maximum time to wait in milliseconds\n\n**Returns:** Array of task results, indexed by task ID\n\n#### `cancel(): bool`\n\nCancel all pending tasks in the group.\n\n**Returns:** True if all tasks were cancelled, false otherwise\n\n## TaskBatch Class\n\nEfficiently processes multiple similar tasks.\n\n### Methods\n\n#### `__construct(array $tasks)`\n\nCreate a new task batch.\n\n**Parameters:**\n- `$tasks`: Array of task definitions (strings or arrays with 'class' and 'params' keys)\n\n#### `dispatch(int $priority = Task::PRIORITY_NORMAL): array`\n\nExecute all tasks in the batch.\n\n**Parameters:**\n- `$priority`: Priority level for all tasks in the batch\n\n**Returns:** Array of task IDs\n\n#### `wait(int $timeout = 30000): array`\n\nWait for all tasks in the batch to complete.\n\n**Parameters:**\n- `$timeout`: Maximum time to wait in milliseconds\n\n**Returns:** Array of task results, indexed by task ID\n\n#### `cancel(): bool`\n\nCancel all pending tasks in the batch.\n\n**Returns:** True if all tasks were cancelled, false otherwise\n\n## TaskManager Class\n\nCore class managing task queues and processing.\n\n### Methods\n\n#### `getInstance(): TaskManager`\n\nGet the singleton instance of the TaskManager.\n\n**Returns:** TaskManager instance\n\n#### `setServer(Server $server): void`\n\nSet the Swoole server instance.\n\n**Parameters:**\n- `$server`: Swoole server instance\n\n#### `registerMiddleware($middleware): self`\n\nRegister global middleware that applies to all tasks.\n\n**Parameters:**\n- `$middleware`: Middleware class name or callable\n\n**Returns:** $this (for method chaining)\n\n#### `enqueue(string $taskClass, array $params = [], int $priority = Task::PRIORITY_NORMAL): int`\n\nAdd a task to the queue for immediate execution.\n\n**Parameters:**\n- `$taskClass`: The full class name of the task to execute\n- `$params`: Parameters to pass to the task's handle method\n- `$priority`: Priority level for the task\n\n**Returns:** Task ID\n\n#### `enqueueDelayed(string $taskClass, array $params = [], int $delayMs = 1000, int $priority = Task::PRIORITY_NORMAL): int`\n\nAdd a task to be executed after a delay.\n\n**Parameters:**\n- `$taskClass`: The full class name of the task to execute\n- `$params`: Parameters to pass to the task's handle method\n- `$delayMs`: Delay in milliseconds before executing the task\n- `$priority`: Priority level for the task\n\n**Returns:** Task ID\n\n#### `enqueueWithRetry(string $taskClass, array $params = [], array $retryOptions = ['attempts' =\u003e 3, 'delay' =\u003e 1000, 'multiplier' =\u003e 2], int $priority = Task::PRIORITY_NORMAL): int`\n\nAdd a task with retry options.\n\n**Parameters:**\n- `$taskClass`: The full class name of the task to execute\n- `$params`: Parameters to pass to the task's handle method\n- `$retryOptions`: Retry configuration\n  - `attempts`: Maximum number of attempts (including the first attempt)\n  - `delay`: Initial delay in milliseconds before retrying\n  - `multiplier`: Multiplier for exponential backoff\n- `$priority`: Priority level for the task\n\n**Returns:** Task ID\n\n#### `getNextTask(): ?array`\n\nGet the next task from the highest priority queue.\n\n**Returns:** Task data array or null if queues are empty\n\n#### `addTaskToGroup(int $taskId, string $groupName): void`\n\nAdd a task to a group.\n\n**Parameters:**\n- `$taskId`: The ID of the task\n- `$groupName`: The name of the group\n\n#### `addTaskToBatch(int $taskId, string $batchId): void`\n\nAdd a task to a batch.\n\n**Parameters:**\n- `$taskId`: The ID of the task\n- `$batchId`: The ID of the batch\n\n#### `waitForGroup(string $groupName, int $timeout = 30000): array`\n\nWait for all tasks in a group to complete.\n\n**Parameters:**\n- `$groupName`: The name of the group\n- `$timeout`: Maximum time to wait in milliseconds\n\n**Returns:** Array of task results, indexed by task ID\n\n#### `waitForBatch(string $batchId, int $timeout = 30000): array`\n\nWait for all tasks in a batch to complete.\n\n**Parameters:**\n- `$batchId`: The ID of the batch\n- `$timeout`: Maximum time to wait in milliseconds\n\n**Returns:** Array of task results, indexed by task ID\n\n#### `cancelTask(int $taskId): bool`\n\nCancel a specific task.\n\n**Parameters:**\n- `$taskId`: The ID of the task to cancel\n\n**Returns:** True if the task was cancelled, false otherwise\n\n#### `cancelGroup(string $groupName): bool`\n\nCancel all tasks in a group.\n\n**Parameters:**\n- `$groupName`: The name of the group\n\n**Returns:** True if all tasks were cancelled, false otherwise\n\n#### `cancelBatch(string $batchId): bool`\n\nCancel all tasks in a batch.\n\n**Parameters:**\n- `$batchId`: The ID of the batch\n\n**Returns:** True if all tasks were cancelled, false otherwise\n\n#### `getTaskStatus(int $taskId): array`\n\nGet the status of a task.\n\n**Parameters:**\n- `$taskId`: The ID of the task\n\n**Returns:** Array with task status information\n\n#### `getMetrics(): array`\n\nGet metrics for monitoring.\n\n**Returns:** Array with metrics:\n- `total_tasks`: Total number of tasks created\n- `completed_tasks`: Number of successfully completed tasks\n- `failed_tasks`: Number of failed tasks\n- `retried_tasks`: Number of retried tasks\n- `cancelled_tasks`: Number of cancelled tasks\n- `average_execution_time`: Average task execution time in seconds\n\n## TaskHandler Class\n\nIntegrates the TaskManager with Swoole.\n\n### Methods\n\n#### `init(Server $server): void`\n\nInitialize the task handler with the server.\n\n**Parameters:**\n- `$server`: Swoole server instance\n\n**Example:**\n```php\n$server = new Swoole\\Server('0.0.0.0', 9501);\n$server-\u003eset([\n    'worker_num' =\u003e 4,\n    'task_worker_num' =\u003e 8,\n    'task_enable_coroutine' =\u003e true,\n]);\n\nSwooleTaskHandler::init($server);\n```\n\n#### `handleTask(array $data)`\n\nHandle a task execution.\n\n**Parameters:**\n- `$data`: Task data array\n\n**Returns:** The result from the task's handle method, or an error array\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fody-dev%2Ftask","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fody-dev%2Ftask","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fody-dev%2Ftask/lists"}