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

524 Likes
Avoiding wait() and why
BehaviorTrees3 + BTrees Visual Editor v3.0
Roblox LSP - Full Intellisense for Roblox and Luau!
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
Simple and Free | Cooldown/Debounce data handling module
Welder - a simple plugin about constraints
Why does my game lag?
Code not executing with a big wait like wait(512)
Save your player data with ProfileService! (DataStore Module)
Minerva | Changelogs
Best way to build a 5 minute timer?
Task.wait() for stepped
Task.wait() for stepped
Tutorial on basic things you need to know as a beginner to start scripting
Replicate your states with ReplicaService! (Networking system)
Animation Play Load
Debounce Not Working
Server memory reaches 5 GB Why?
Continuing Functions from Loops
Instance Based Game Pass System
How can I improve this horror game environment code?
Tree Generator Module
Speed of camera and part changes by the FPS
Instance Based Game Pass System
Tool Animation loader
Properly destroy player on leave
New Spawn() function?
Alternatives to "while true do" in my script?
Alternatives to "while true do" in my script?
Area Detection cooldown + kill script
How do I use a coroutine without a function?
About using RunService events
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)
[SOLVED] Different ways to delay a script without using wait() twice
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
Difference between wait() and task.wait()?
Laser not moving fast enough
Using coroutine.yield() in OnServerInvoke will not respond to client
How to make Confetti appear on part Touched!

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.

64 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()?

17 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…

31 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

15 Likes

I believe this should answer your question:

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

8 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)

3 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.

24 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?

15 Likes

What is the fastSpawn pattern?

5 Likes

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

2 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”.

8 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)

3 Likes

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

7 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).

4 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?

7 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!

32 Likes