Smart Task Scheduler System
Marketplace Link:
Introduction
This Smart Task Scheduler System offers a powerful toolset for effectively managing, prioritizing, and executing looped tasks within Lua scripts. This system provides a comprehensive solution for organizing tasks, enabling users to customize execution intervals, priorities, and execution contexts. At its core, the main script, referred to as “Processor,” interacts with the sophisticated MinHeap module to ensure optimal task scheduling. This documentation provides a detailed overview of the Task Scheduler’s features, including comprehensive explanations of each function and practical application examples.
Core Script Overview
The Processor script serves as the foundation of the Task Scheduler System. It empowers users to seamlessly manage tasks, control execution sequences, and streamline workflows.
Function List
Here is a comprehensive list of functions offered by the Processor script:
- getFunctionId(taskName: string) → string: Generates a unique identifier for tasks, with an optional task name.
- ExecuteFunction(task: Task): Executes the function associated with a task, handling both single functions and groups of functions.
- Run(): Executes tasks from the MinHeap, managing execution based on priority and delay.
- addTask(task: Function__or__Function_Table, delay: NumberValue, priority: priority, SpawnedTask: BoolValue, key: string | NumberValue): Adds a new task for execution.
- addTaskIntoTaskGroup(key: string | NumberValue, newTask: Function, newTaskKey: string | NumberValue): Adds a new function to an existing task group for parallel execution.
- removeTaskFromTaskGroup(key: string | NumberValue, desiredTaskKey: string | NumberValue): Removes a function from an existing task group.
- changeTaskDelay(key: string | NumberValue, newDelay: NumberValue) → boolean: Modifies the delay of a specific task.
- pauseTask(key: string | NumberValue, TimeOfPausing: NumberValue): Pauses the execution of a specific task for a specified duration.
- pauseAllTasks(TimeOfPausing: NumberValue): Pauses the execution of all tasks for a specified duration.
- continueTask(key: string | NumberValue) → boolean: Continues the execution of a paused task.
- continueAllpausedTasks(): Resumes the execution of all paused tasks.
- testForTask(key: string | NumberValue) → boolean: Checks if a task with a specific key exists in the system.
- removeTask(key: string | NumberValue) → boolean: Removes a task from the system based on its key.
- getAmountRunning() → number: Retrieves the current count of tasks running within the system.
- HeapInfo() → MinHeap: Retrieves information about the MinHeap’s state.
Core Concepts
Task Execution
The Processor executes tasks based on their priority and delay. Higher-priority tasks are executed before lower-priority ones. Tasks can be single functions or groups of functions executed in parallel.
Task Groups
Tasks can be grouped together for parallel execution. This feature is useful when multiple functions need to run concurrently.
Pausing and Resuming
Tasks can be paused for a specified duration or indefinitely. Paused tasks are temporarily halted, allowing for controlled execution sequencing.
Priority-Based Execution
Tasks are executed based on their priority values. Lower numerical priority values indicate higher execution priority.
Practical Examples
Example 1: Single Task Execution
Imagine a scenario where a task named Task1
needs to execute every 2 seconds with a priority of 1. The following code snippet achieves this:
luaCopy code
local Task1 = function()
print("Task1")
end
local TaskId = Processor:getFunctionId("Test")
Processor:addTask(Task1, 2, 1, false, TaskId)
-- To remove the task:
Processor:removeTask(TaskId)
Example 2: Parallel Task Execution
Suppose we have multiple functions (Task1
, Task2
, Task3
, Task4
, Task5
) that should execute concurrently as a single task. Here’s how to organize and execute them:
luaCopy code
local Task1 = function()
print("Task1")
end
-- Define other tasks (Task2, Task3, Task4, Task5)
local TaskGroupId = Processor:getFunctionId("Test")
Processor:addTask({}, 2, 2, true, TaskGroupId)
local Task1Id = Processor:getFunctionId("Test-Task1")
-- Define Task2Id, Task3Id, Task4Id, Task5Id
-- Add tasks to the group
Processor:addTaskIntoTaskGroup(TaskGroupId, Task1, Task1Id)
-- Add other tasks to the group
-- To remove tasks from the group:
Processor:removeTaskFromTaskGroup(TaskGroupId, Task1Id)
-- Remove other tasks from the group
Example 3: Task Execution Ordering
To better understand the execution sequence, let’s examine an example with different task delays, priorities, and processing times. Consider the following setup:
- Task1: Delay: 2; Priority: 1, Spawned: false
- Task2: Delay: 1; Priority: 1, Spawned: false
- Task3: Delay: 0.25; Priority: 2, Spawned: false
- Task4: Delay: 3; Priority: 3, Spawned: true
- Task5: Delay: 1.5; Priority: 4, Spawned: false
With processing times as follows:
- Task1 process time: 0.5 seconds
- Task2 process time: 0.75 second
- Task3 process time: 0.3 seconds
- Task4 process time: 0.05 seconds
- Task5 process time: 0.4 seconds
In an execution cycle, the timeline would look like this:
- Task1 starts at time 0, processes for 0.5 seconds.
- Task2 starts at time 1, processes for 0.75 seconds.
- Task3 starts at time 1.75, processes for 0.3 seconds.
- Task4 starts at time 3 (spawned task), processes for 0.05 seconds.
- Task5 starts at time 3, processes for 0.4 seconds.
This is a simplyfied example.
A cycle where tasks trap each other in an infinite priority loop can not accur.
Example 4: A Real use case in one of my games as example:
local AIHandler = {}
local TweenService = game:GetService("TweenService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Processor = require(ReplicatedStorage:WaitForChild("Processor"))
local Animations = script.Parent:WaitForChild("Animations")
local EntitySettings = require(script.Parent.EntitySettings)
local EntityNorms = EntitySettings.Norms
local Sounds = script.Parent.Sounds
local EntitiesAITaskId = Processor:getFunctionId("EntitesAIProcessor")
Processor:addTask({}, 1.5, 3, true, EntitiesAITaskId)
function testForLand(DestinationPos, ignoreMaterials)
-- ...
end
function playAnimalSound(model)
-- ...
end
AIHandler.AIs = {
Sheep = function(model, Humanoid)
spawn(function()
local AITaskId = Processor:getFunctionId("SheepAI")
local currentTimeCached = 0
local finishedAnimation = true
local function AITask()
if model.Parent ~= ReplicatedStorage:WaitForChild("CachedEntities") and finishedAnimation then
pcall(function()
finishedAnimation = false
local Area = Vector3.new(50, 0, 50)
local currentPoint = model.PrimaryPart.Position
local RandomPoint = Vector3.new(
math.random(-Area.X / 2, Area.X / 2),
0,
math.random(-Area.Z / 2, Area.Z / 2)
)
local Destination = currentPoint + RandomPoint
local Animation = Humanoid:LoadAnimation(Animations.Sheep)
if testForLand(Destination, {Enum.Material.Water, Enum.Material.Sand}) then
Humanoid:MoveTo(Destination)
Animation:Play()
Humanoid.MoveToFinished:Wait()
Animation:Stop()
playAnimalSound(model)
local rngWait = math.random(1,4)
wait(rngWait)
end
finishedAnimation = true
end)
else
currentTimeCached += 3
end
if model.Parent == nil or currentTimeCached >= EntityNorms.DespawnTimeIfCached then
script.Parent.DisconnectHumanoidConnections:Fire(model)
if model.Parent ~= nil then
model:Destroy()
end
Processor:removeTaskFromTaskGroup(EntitiesAITaskId, AITaskId)
end
end
Processor:addTaskIntoTaskGroup(EntitiesAITaskId, AITask, AITaskId)
end)
end,
-- rest of the table
}
-- ...
return AIHandler
Conclusion
The Task Scheduler System simplifies task management, priority handling, and execution sequencing, making it an indispensable asset for optimizing workflows in a variety of systems. Its adaptability, combined with the streamlined organization of the MinHeap module, empowers users to create sophisticated task-based systems with ease.