🔍 Code Extractor

function complete_task

Maturity: 39

Updates the status of a task to 'completed' in a thread-safe manner, storing the result and completion timestamp.

File:
/tf/active/vicechatdev/docchat/app.py
Lines:
184 - 190
Complexity:
simple

Purpose

This function is part of a task management system that tracks asynchronous operations. It safely updates a task's state in a shared dictionary (active_tasks) using a lock to prevent race conditions. The function marks a task as completed, stores its result, and records the completion time. This is typically used in web applications or background job processing systems where tasks need to be tracked across multiple threads.

Source Code

def complete_task(task_id, result):
    """Mark task as completed"""
    with task_lock:
        if task_id in active_tasks:
            active_tasks[task_id]['status'] = 'completed'
            active_tasks[task_id]['result'] = result
            active_tasks[task_id]['completed_at'] = datetime.now()

Parameters

Name Type Default Kind
task_id - - positional_or_keyword
result - - positional_or_keyword

Parameter Details

task_id: Unique identifier for the task to be marked as completed. Expected to be a string (likely a UUID) that exists as a key in the active_tasks dictionary. If the task_id doesn't exist in active_tasks, the function silently does nothing.

result: The result/output of the completed task. Can be any data type (string, dict, list, object, etc.) depending on what the task produces. This value is stored in the task's dictionary under the 'result' key for later retrieval.

Return Value

This function returns None (no explicit return statement). It performs side effects by modifying the active_tasks dictionary in place.

Dependencies

  • datetime
  • threading

Required Imports

from datetime import datetime
from threading import Lock

Usage Example

from datetime import datetime
from threading import Lock

# Required global setup
task_lock = Lock()
active_tasks = {}

# Create a task first
task_id = 'task-123'
active_tasks[task_id] = {
    'status': 'running',
    'created_at': datetime.now()
}

# Complete the task with a result
result_data = {'output': 'Task finished successfully', 'count': 42}
complete_task(task_id, result_data)

# Check the updated task
print(active_tasks[task_id]['status'])  # Output: 'completed'
print(active_tasks[task_id]['result'])  # Output: {'output': 'Task finished successfully', 'count': 42}
print(active_tasks[task_id]['completed_at'])  # Output: datetime object

Best Practices

  • Always ensure task_lock and active_tasks are properly initialized as global variables before calling this function
  • The task_id should exist in active_tasks before calling this function, though the function handles missing keys gracefully
  • This function is thread-safe due to the lock, making it suitable for multi-threaded environments
  • Consider implementing error handling or logging if the task_id doesn't exist in active_tasks
  • The function assumes active_tasks[task_id] is a dictionary with modifiable keys
  • Pair this function with corresponding functions like create_task() and get_task_status() for complete task lifecycle management
  • Consider adding validation to ensure the task is in a valid state before marking as completed (e.g., not already completed)

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function complete_task_v1 93.1% similar

    Thread-safe function that marks a task as completed by updating its status, storing the result, and recording the completion timestamp in a shared task dictionary.

    From: /tf/active/vicechatdev/vice_ai/app.py
  • function update_task_progress 78.9% similar

    Thread-safe function that updates the progress and timestamp of an active task identified by task_id in a shared dictionary.

    From: /tf/active/vicechatdev/docchat/app.py
  • function fail_task_v1 77.9% similar

    Marks a task as failed by updating its status, recording the error message, and setting the completion timestamp in a thread-safe manner.

    From: /tf/active/vicechatdev/docchat/app.py
  • function fail_task 76.0% similar

    Marks a task as failed by updating its status, recording the error message, and setting the completion timestamp in a thread-safe manner.

    From: /tf/active/vicechatdev/vice_ai/app.py
  • function get_task_status_v1 70.9% similar

    Thread-safe function that retrieves the current status of a task from a shared dictionary using a task identifier.

    From: /tf/active/vicechatdev/docchat/app.py
← Back to Browse