🔍 Code Extractor

function complete_task_v1

Maturity: 39

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.

File:
/tf/active/vicechatdev/vice_ai/app.py
Lines:
60 - 66
Complexity:
simple

Purpose

This function is used in a multi-threaded task management system to safely update task state when a task finishes execution. It ensures thread-safe access to the active_tasks dictionary using a lock, preventing race conditions when multiple threads attempt to update task statuses simultaneously. The function is typically called by worker threads or task executors to signal task completion and store results for later retrieval.

Source Code

def complete_task(task_id, result):
    """Mark task as completed with result"""
    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 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 Python object (string, dict, list, etc.) that represents the task's outcome. This value is stored in the task's metadata for later retrieval by the task requester.

Return Value

This function returns None (implicitly). It performs side effects by modifying the active_tasks dictionary in place, updating the task's status to 'completed', storing the result, and recording the completion timestamp.

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
task_id = 'task-123'
active_tasks[task_id] = {
    'status': 'running',
    'created_at': datetime.now()
}

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

# Verify task completion
print(active_tasks[task_id]['status'])  # Output: 'completed'
print(active_tasks[task_id]['result'])  # Output: {'output': 'Task completed 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 by doing nothing
  • This function is thread-safe and can be called from multiple threads simultaneously
  • Consider implementing error handling or logging if you need to track attempts to complete non-existent tasks
  • The result parameter can be any serializable object if tasks need to be persisted or transmitted
  • Pair this function with a task cleanup mechanism to prevent active_tasks from growing indefinitely
  • Consider adding validation to ensure tasks aren't completed multiple times if that's a concern for your use case

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function complete_task 93.1% similar

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

    From: /tf/active/vicechatdev/docchat/app.py
  • function fail_task_v1 79.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/docchat/app.py
  • function fail_task 76.6% 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 update_task_progress 75.4% 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 get_task_status_v1 72.6% 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