Task Library - Now Available!

Hey developers,

We have just enabled a brand new library that you can use in your projects. The task library allows you to talk directly with our engine’s task scheduler to manage and schedule code. It features a number of new methods as well as some improvements to existing methods.

Details

task.spawn

Takes a thread or function and resumes it immediately through the engine’s scheduler. Additional arguments are passed to the thread or function being resumed.

void task.spawn(function | thread, ...args)

This is particularly useful when calling a function which may yield when iterating over a set of objects:

local function playerAdded(player)
    ...
    (yield)
end

for _, player in ipairs(Players:GetPlayers()) do
    task.spawn(playerAdded, player)
end

task.spawn is based on the fastSpawn pattern rather than being a replacement for spawn. We recommend you use this method where you would otherwise use fastSpawn.

task.defer

Takes a thread or function and defers it until the next resumption cycle at which point it is resumed with the engine’s scheduler. Additional arguments are passed to the thread or function being resumed.

void task.defer(function | thread, ...args)

You should typically use this when you want similar behavior to task.spawn but don’t care about the thread running immediately.

task.defer(print, "A")
print("B")
--> B
--> A

task.defer is an improved version of spawn which schedules a thread to be resumed as soon as possible (but not immediately) without any throttling.

task.delay

Takes a thread or function and schedules it for resumption after the given amount of time has elapsed on the next Heartbeat step. The thread is resumed with built-in error handling and support for other engine features. Any additional arguments are passed to the thread or function being resumed.

void task.delay(duration, function | thread, ...args)

Since the actual delay time may vary it can be calculated by passing the current time as an argument.

task.delay(2, function (scheduledTime)
    print(os.clock() - scheduledTime) --> 2.038702
end, os.clock())

A duration of zero will result in the thread or function being resumed on the next step.

task.delay is an improved version of delay which schedules a thread to be resumed after some time has elapsed without throttling.

task.wait

Yields the current thread until the given duration (in seconds) has elapsed and then resumes the thread on the next Heartbeat step.

elapsed task.wait(duration=0)

Since the actual yield time may vary, this method returns it for convenience.

local elapsedTime = task.wait(2) -- wait for 2 seconds
print(elapsedTime) --> 2.0792941

If no duration is given the duration will default to zero meaning the thread will automatically resume on the next step.

task.wait()
-- is equivalent in behavior to
RunService.Heartbeat:Wait()

task.wait is an improved version of wait which schedules the current thread to be resumed after some time has elapsed without throttling.

Existing Methods

We will eventually mark the existing methods (spawn, delay, and wait) as deprecated in favor of their alternatives however they will continue to work as they do now for the foreseeable future and we have no plans to change this.

See Also

664 Likes
Avoiding wait() and why
Roblox LSP - Full Intellisense for Roblox and Luau!
Why does my game lag?
I need help with choosing a random Player
Is the only way to detect whether it has been X amount of minutes by using wait() or loops?
Improving this Cooldown module
Difference between wait() and task.wait()?
Task.delay vs task.wait
Server memory reaches 5 GB Why?
What's diffirence between wait() and task.wait()
Task.wait(n) vs wait(n)
Welder - a simple plugin about constraints
What is delay/task.delay used for?
The Wait() in my code won't work properly (coroutine.wrap)
Worth using a wait() if it slows generation way down?
Why does this script run 1 time? (Sometimes 2)
Tutorial on basic things you need to know as a beginner to start scripting
Best way to build a 5 minute timer?
How to make Confetti appear on part Touched!
New Spawn() function?
Whats wrong with my script?
Holy Mother of Memory Leaks
"Pause" Code Until Critera is Met?
Save your player data with ProfileService! (DataStore Module)
Is there anything smaller than wait()?
Replicate your states with ReplicaService! (Networking system)
Animation Play Load
Debounce Not Working
Why does my ragdolls take a while to get up?
Continuing Functions from Loops
How can I improve this horror game environment code?
Things to look out for when using Network Events (RenderStepped, Stepped, Heartbeat)
Tool Animation loader
Tree Generator Module
Help with debris system
<<attempt to index nil with 'instance'>> occuring randomly
Speed of camera and part changes by the FPS
Help with implementing spawn, or coroutine
Can this code be cleaner?
Wait until something is true
How can I improve my platform button code?
Region3 error in game
Help upgrading a gun system
To Detect players joining and leaving in a table, Would this work?
Launch Pad Scripting
Why is task not showing up?
"Infinite yield possible on RemoteEvent"
Avoiding wait() and why
Task.wait() for stepped
How do I improve this little script?
Instance Based Game Pass System
Instance Based Game Pass System
BehaviorTrees3 + BTrees Visual Editor v3.0
Ui not Tweening
Help with Stamina System (Memory Leak)
Area Detection cooldown + kill script
How to implement multiple infinite loops?
Two endings happening at once
How can I improve this raycast system?
Should a player script be in ServerScriptService?
Why is wait() important?
How do you make a door open after X amount of time has passed?
Is there a way to make the script keep running while executing a function()
Developer Community 2021 Wrap-Up
Does anybody know how to fix this Rich Text bug?!
ScreenGUI Changing Tips [SOLVED]
Roblox OOP cooldown feedback
Sliding system with cooldown (R15)
Task.wait() vs wait() in loops
How do I get the task library with Luau console?
Difference between task.wait and wait?
HttpQueue - Forget about rate limiting, focus on the rest!
Does Roblox Studio's "wait(number)" accurate to real life time?
Which is better while loops or runservice loops
How can I make a tower defense attacking system?
I need to make my scripts run faster
[Improved] How to Actually Improve Performance in Your Games
Coin Collecting has Cooldown
Code grabs players one by one, individually
Ledge grabbing script not properly working
Need help with an obby air vent
Deeper Look into Wait()
Hunger/thirst depletion
What can I remove/change/add (meteor script)
How to make a Countdown multiplier faster than 32x?
While wait() do vs runservice renderstepped
Help with GUI script
Should I be cloning scripts to make new threads or use corountines?
Why Decal (face) on players head won't "Fade" or "Remove"?
How to save a TextBox's Text
Avoid using while true do & while wait() do!
Absurdly long rendering times when a certain GUI shows in my game
Server Time Sign
Gravity Pull Effect
Minerva | Changelogs
Code not executing with a big wait like wait(512)
Simple and Free | Cooldown/Debounce data handling module
Task.wait() for stepped
Wait() vs task.wait()
Exhausted allowed execution time error with true loop: Fix
Wait() vs task.wait()
How To Keep Code Clean Part: 1
How to break this for loop?
Roll Jump kind of queues itself until I jump
Uses of different "waits" in scripting
Should I use Wait() or Task.Wait()
Tool Gets automatically picked up even though Touch Interests are destroyed
What is the difference between wait() and task.wait()
How to make a game lag less
Trying to make 2 leaderstats
Does Spawn(function()) stilll throttle the code?
What would be better for a singleplayer game with almost only localscripts?
erverScriptService.Script:14: invalid argument #2 to 'random' (interval is empty)
Why is Wait So Bad?
Improving my code
Cooldown for tool activated
Modules for a Donation Game
How to avoid yielding for my cooldown functions
Why does while true do go slow in servers with 20 players?
Checking if a variable changed
Should I use task.wait() over wait?
Alternatives to "while true do" in my script?
Frame tween not working
Is this a viable way to save data?
Esc Menu Effect [Blackout]
Alternatives to "while true do" in my script?
How do I use a coroutine without a function?
How to delete hats off a character?
Hello people, quick help here
How to constantly check if a player is touching a part?
Rate my DOF code
Removing a wait(), functions are called in the wrong order. Is the ModuleScript implemented correctly?
I need help making a MUSIC GUI where all players can hear, k everything updates but buggy omg
Invalid argument #3 (string expected, got Instance)
Need help with while true loops
Using coroutine.yield() in OnServerInvoke will not respond to client
What are the difference between these functions?
Script not cloning fire to all players (i figured out the bug but idk how to fix it for some reason)
Looking for feedback on more accurate wait() I made(faster than task.wait())
Heartbeat is worse than while true do wait()?
Heartbeat is worse than while true do wait()?
My script is very laggy
Crouch script not working
[SOLVED] Different ways to delay a script without using wait() twice
Accounting for Player Leave on a Roundbased System
RoadNames: a free, easy-to-use road-naming system
Children are not detected in GetChildren()
Player.Character:PivotTo(CFrame)/:MoveTo(Vector3) not Working
Issues with things running in parallel
I need help; when a person touches an object, a screen UI text fades in and out
Night Vision Thing Won't Work
I need help; when a person touches an object, a screen UI text fades in and out
Laser not moving fast enough
Properly destroy player on leave

This topic was automatically opened after 7 minutes.

Super excited to get these in my projects already. The task APIs look super easy to use, introduce to novice developers and get them used to new patterns. I too look forward to adopting new patterns in my code involving them. This could also help very much with getting used to deferred events which I initially resisted heavily.

:heart: the improved versions of old functions that were particularly discouraged (e.g. delay), especially wait and how it’s based on Heartbeat frequency. Don’t have to write my own boilerplate for that anymore or abuse Promises to get what I need. Same goes with task.spawn for fastSpawn. Less boilerplate and I can use these better versions rather than the ones based on the old frequencies.

Outstanding work. Thank you, engineers!

Also, alas begone, legacy wait. Get outta here.

79 Likes

Question:

Is task.wait() with no parameters an alternative to using RunService.Heartbeat:Wait()?

There was this article about not using wait() with no parameters.

Or should we continue using RunService.Heartbeat:Wait()?

22 Likes

Yes, task.wait() is now equivalent to RunService.Heartbeat:Wait(), and a lot more convenient too. The amount of time spent typing that out saved is astonishing…

46 Likes

Is there any reason you didn’t just change the default behaviours of those functions, and instead add a new task library? Does this have something to do with parallel lua :flushed:

Anway’s glad that useless old function has now been given a replacement

22 Likes

I believe this should answer your question:

The reason using wait() with no parameters is bad is because it (task.wait()) is

13 Likes

i’m wondering if this wait() alternative:

function Halt(Duration)
	--// Arguments: (Duration[Number])
	
	Duration = (Duration or 0)
	local cur = 0;
	if (Duration <= 0) then
		Heartbeat:Wait();
	end
	while cur < Duration do
		cur += Heartbeat:Wait();
	end
	return cur;
	
end

is the same as:

task.wait()
11 Likes

(post withdrawn by author, will be automatically deleted in 1 hour unless flagged)

8 Likes

It should be noted that results of these aren’t equivalent:

task.spawn(function()
	print(task.wait())
end)
task.spawn(function()
	print(game:GetService"RunService".Heartbeat:Wait())
end)

task.wait()'s DeltaTime result will count from the time of the call, while Heartbeat:Wait() will count from the previous Heartbeat.


Also, task.delay() causes a crash instead of an error.

26 Likes

Is this almost like some kind of task manager for Studio?

3 Likes

Because you can’t do Heartbeat:Wait(2) since :Wait() function on RBXScriptSignals doesn’t take any arguments?

16 Likes

What is the fastSpawn pattern?

6 Likes

So what’s the difference of task.wait, task.spawn, and wait, spawn?

3 Likes

I’m still struggling to understand use cases for task.defer. I understand how it works and how it fits into the library but under what circumstances would you want code to run at some predetermined point later in time that you have no control over? Is there any real benefit in doing so?

I also don’t understand this. How is it not a replacement for spawn? And wasn’t the original fastspawn method implemented with BindableEvents? With deferred events that would mean that it wouldn’t be an immediate resumption, unless of course I’m misinterpreting the meaning of “fastSpawn pattern”.

12 Likes

deferred on Nevermore (originally fastSpawn)

“An expensive way to spawn a function. However, unlike spawn(), it executes on the same frame, and unlike coroutines, does not obscure errors.”

(edit: changed link to folder with README, was originally set to a release branch)

5 Likes

I assume for legacy purposes, old games experiences whose behavior could be compromised if they just redo the old functions.

11 Likes

Will documentation for task happen soon? I’d expect it to be available on the developer hub for more info and on task scheduler article on availability of a class (aka today).

5 Likes

Hmmm… what is happening??


Is this basically like coroutine? I mean, I am a builder, not knowing much about these, but isn’t it the same thing?

9 Likes

Updated my “Spawn is Evil” article to just point to the new task library. Glad that this problem finally has an easy solution that doesn’t require several paragraphs to explain!

34 Likes