The Workers module manages background tasks, asynchronous operations, and specialized worker threads for the Game Macro system.
| English Version | 中文版本 |
The Workers module provides:
The workers system is designed for specialized background operations:
Main worker management and coordination system.
Manages specialized worker threads for different tasks.
Worker := {
Id: 1,
Name: "PixelDetectionWorker",
Type: "Background",
Priority: "Normal",
IntervalMs: 50,
IsRunning: false,
LastRunTime: 0,
ErrorCount: 0,
ResourceUsage: {
CPU: 5.2,
Memory: 15.3
},
Dependencies: ["PixelEngine"]
}
Manages long-running background tasks.
BackgroundTask := {
Id: 1,
Name: "ProfileAutoSave",
Type: "Periodic",
IntervalMs: 30000,
IsEnabled: true,
LastExecution: 0,
ExecutionCount: 0,
Function: "AutoSaveProfiles",
Parameters: {}
}
Manages asynchronous operations with callbacks.
AsyncOperation := {
Id: 1,
Name: "ImageProcessing",
Type: "Async",
Status: "Pending",
StartTime: 0,
EndTime: 0,
Result: {},
Callback: "ProcessImageComplete",
ErrorHandler: "ProcessImageError"
}
Initializes the workers system.
Parameters: None
Returns: Boolean indicating success
Starts all enabled workers.
Parameters: None
Returns: Boolean indicating success
Stops all workers.
Parameters: None
Returns: Boolean indicating success
Pauses all workers.
Parameters: None
Returns: Boolean indicating success
Resumes all workers.
Parameters: None
Returns: Boolean indicating success
Creates a new worker.
Parameters:
workerConfig (Map): Worker configurationReturns: Worker ID
Starts a specific worker.
Parameters:
workerId (Integer): Worker identifierReturns: Boolean indicating success
Stops a specific worker.
Parameters:
workerId (Integer): Worker identifierReturns: Boolean indicating success
Gets the state of a specific worker.
Parameters:
workerId (Integer): Worker identifierReturns: Worker state map
Adds a new background task.
Parameters:
taskConfig (Map): Task configurationReturns: Task ID
Removes a background task.
Parameters:
taskId (Integer): Task identifierReturns: Boolean indicating success
Executes a background task immediately.
Parameters:
taskId (Integer): Task identifierReturns: Boolean indicating success
Creates a new async operation.
Parameters:
opConfig (Map): Operation configurationReturns: Operation ID
Starts an async operation.
Parameters:
opId (Integer): Operation identifierReturns: Boolean indicating success
Gets the status of an async operation.
Parameters:
opId (Integer): Operation identifierReturns: Operation status map
; Create a pixel detection worker
pixelWorker := {
Id: 1,
Name: "PixelDetectionWorker",
Type: "Background",
Priority: "High",
IntervalMs: 50,
Dependencies: ["PixelEngine"]
}
workerId := Workers_CreateWorker(pixelWorker)
; Start the worker
if (Workers_StartWorker(workerId)) {
Logger_Info("Workers", "Pixel detection worker started", Map("workerId", workerId))
}
; Create auto-save background task
autoSaveTask := {
Id: 1,
Name: "ProfileAutoSave",
Type: "Periodic",
IntervalMs: 30000, ; 30 seconds
IsEnabled: true,
Function: "AutoSaveProfiles",
Parameters: {}
}
taskId := Workers_AddBackgroundTask(autoSaveTask)
; Auto-save function
AutoSaveProfiles() {
if (App["ProfileData"]["IsModified"]) {
Storage_SaveProfile(App["CurrentProfile"])
Logger_Info("Workers", "Profile auto-saved")
}
}
; Create async image processing operation
imageOp := {
Id: 1,
Name: "ImageProcessing",
Type: "Async",
Callback: "ProcessImageComplete",
ErrorHandler: "ProcessImageError"
}
opId := Workers_CreateAsyncOperation(imageOp)
; Start the operation
Workers_StartAsyncOperation(opId)
; Callback functions
ProcessImageComplete(result) {
Logger_Info("Workers", "Image processing completed", result)
UI_UpdateImage(result["ProcessedImage"])
}
ProcessImageError(error) {
Logger_Error("Workers", "Image processing failed", error)
UI_ShowError("Image processing error")
}
; Worker with resource monitoring
resourceWorker := {
Id: 2,
Name: "ResourceMonitor",
Type: "Monitoring",
Priority: "Low",
IntervalMs: 1000,
Dependencies: []
}
resourceId := Workers_CreateWorker(resourceWorker)
; Worker function with resource monitoring
Workers_RegisterWorkerFunction(resourceId, Func("MonitorResources"))
MonitorResources() {
; Monitor system resources
cpuUsage := GetCPUUsage()
memoryUsage := GetMemoryUsage()
; Log resource usage
Logger_Debug("Workers", "Resource usage", Map(
"CPU", cpuUsage,
"Memory", memoryUsage
))
; Adjust worker priorities based on resource usage
if (cpuUsage > 80) {
Workers_AdjustPriorities("Low")
}
}
; Worker with error handling
errorWorker := {
Id: 3,
Name: "ErrorHandlingWorker",
Type: "ErrorRecovery",
Priority: "Normal",
IntervalMs: 5000,
Dependencies: []
}
errorId := Workers_CreateWorker(errorWorker)
; Error handling function
Workers_RegisterWorkerFunction(errorId, Func("HandleWorkerErrors"))
HandleWorkerErrors() {
; Check for worker errors
errorWorkers := Workers_GetErrorWorkers()
for worker in errorWorkers {
Logger_Warning("Workers", "Worker error detected", Map(
"workerId", worker["Id"],
"errorCount", worker["ErrorCount"]
))
; Attempt recovery
if (worker["ErrorCount"] < 3) {
Workers_RestartWorker(worker["Id"])
} else {
; Too many errors, disable worker
Workers_StopWorker(worker["Id"])
Logger_Error("Workers", "Worker disabled due to errors", Map("workerId", worker["Id"]))
}
}
}
Worker settings are stored in the main configuration:
App["WorkerConfig"] := {
MaxWorkers: 5,
DefaultInterval: 100,
ResourceMonitoring: true,
AutoRecovery: true,
MaxErrorCount: 3
}
Worker configurations can be profile-specific:
profile["Workers"] := [
{
Name: "PixelDetection",
Interval: 50,
Priority: "High",
Enabled: true
},
{
Name: "ResourceMonitor",
Interval: 1000,
Priority: "Low",
Enabled: true
}
]
The workers module includes comprehensive error handling:
The module provides a debugging interface for real-time monitoring:
; Enable worker debugging
Workers_EnableDebug()
; Get debug information
debugInfo := Workers_GetDebugInfo()
All worker activities are logged for troubleshooting: