> For the complete documentation index, see [llms.txt](https://openjs.wiki.gd/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://openjs.wiki.gd/apis-and-tools/globals/task.md).

# task

## Overview: <a href="#overview" id="overview"></a>

<table data-header-hidden><thead><tr><th>Functions:</th></tr></thead><tbody><tr><td>Functions:</td></tr><tr><td><pre class="language-javascript"><code class="lang-javascript">task.spawn(function) ⇒ taskId
</code></pre></td></tr><tr><td><pre class="language-javascript"><code class="lang-javascript">task.main(function) ⇒ taskId
</code></pre></td></tr><tr><td><pre class="language-javascript"><code class="lang-javascript">task.entitySchedule(entity, function) ⇒ taskId
</code></pre></td></tr><tr><td><pre class="language-javascript"><code class="lang-javascript">task.thread(pluginName) ⇒ taskId
</code></pre></td></tr><tr><td><pre class="language-javascript"><code class="lang-javascript">task.threadType() ⇒ string
</code></pre></td></tr><tr><td><pre class="language-javascript"><code class="lang-javascript">task.latch() ⇒ latch-class
</code></pre></td></tr><tr><td><pre class="language-javascript"><code class="lang-javascript">task.delay(delay, function) ⇒ taskId
</code></pre></td></tr><tr><td><pre class="language-javascript"><code class="lang-javascript">task.repeat(delay, period, function) ⇒ taskId
</code></pre></td></tr><tr><td><pre class="language-javascript"><code class="lang-javascript">task.cancel(taskId)
</code></pre></td></tr><tr><td><pre class="language-javascript"><code class="lang-javascript">task.bindToUnload(function)
</code></pre></td></tr><tr><td><pre class="language-javascript"><code class="lang-javascript">task.wait(time) ⇒ boolean &#x26; yields
</code></pre></td></tr><tr><td><pre class="language-javascript"><code class="lang-javascript">task.waitForScript(scriptName) ⇒ yields
</code></pre></td></tr><tr><td><pre class="language-javascript"><code class="lang-javascript">task.waitForPlugin(pluginName) ⇒ yields
</code></pre></td></tr></tbody></table>

## API Reference

## `spawn()` <a href="#spawn" id="spawn"></a>

Runs a function asynchronously.

* **Bukkit**: Uses async scheduler
* **Folia**: Runs on a separate thread

```js
task.spawn(function() {
    log.info("Async execution")
})
```

**Parameters:**

* `function` *(Function)*\
  Function to execute.

**Returns:**

* `taskId` *(Number)*\
  Identifier used to cancel the task.

***

## `main()`

Executes a function safely on the server main thread. (If on Folia use [`task.entitySchedule(..)`](#entityschedule) instead)

```js
task.main(function() {
    log.info("Main thread execution")
})
```

**Parameters:**

* `function` *(Function)*\
  Function to execute.

**Returns:**

* `taskId` *(Number)*

***

## `entitySchedule()`

Schedules a task bound to a specific entity. (Folia alternative to [`task.main(..)`](#main))

```js
task.entitySchedule(player, function() {
    player.sendMessage("Hello")
})
```

**Parameters:**

* `entity` *(Entity)*\
  The entity to bind the task to.
* `function` *(Function)*\
  Function to execute.

**Returns:**

* `taskId` *(Number)*

***

## `thread()`

Executes a function parallel on a thread.

```js
task.thread(function() {
    log.info("External thread execution")
})
```

**Parameters:**

* `function` *(Function)*\
  Function to execute.

**Returns:**

* `taskId` *(Number)*

***

## `threadType()`

Returns a string indicating in which kind of thread the code is running.

```js
log.info("Thread type is: "+ task.threadType())
```

**Parameters:**

* `None`&#x20;

**Returns:**

* `taskType` *(String)* \[Examples: "MAIN" "THREAD "POOL"]

***

## `latch()`

`task.latch()` creates a synchronization primitive for passing values between tasks (threads). It can be used to wait for an event from another thread, listen for multiple invocations, or fire a value to a connected handler.

```javascript
const latch = task.latch()

// In one task
task.thread(() => {
    latch.invoke("Hello")
})

// In another task
const result = latch.wait()   // "Hello"
```

#### Latch Object

The returned latch provides these methods:

***

**`latch.wait()`**

Blocks the current thread until `latch.invoke(value)` is called on this latch. Returns the value passed to `latch.invoke()`.

**Returns:** the invoked value, or `null` if the latch is destroyed.

***

**`latch.listen(function)`**

Registers a callback that will be called every time `latch.invoke(value)` is called (including future invocations). The callback receives the invoked value as its argument.

| Parameter  | Type       | Description               |
| ---------- | ---------- | ------------------------- |
| `function` | `Function` | `function(value) { ... }` |

**Returns:** `void`

***

**`latch.invoke(value)`**

Sends a value to the latch, unblocking any waiting `latch.wait()` calls and triggering any listeners.

| Parameter | Type | Description               |
| --------- | ---- | ------------------------- |
| `value`   | `*`  | Any value to be delivered |

**Returns:** `void`

***

**`latch.connect(function)`**

Sets a handler that will be called when `latch.fire(value)` is called. Only one handler can be connected at a time; subsequent calls replace it.

| Parameter  | Type       | Description               |
| ---------- | ---------- | ------------------------- |
| `function` | `Function` | `function(value) { ... }` |

**Returns:** `void`

***

**`latch.fire(value)`**

Calls the currently connected handler (if any) with the given value. Does **not** affect waiting or listening.

| Parameter | Type | Description                      |
| --------- | ---- | -------------------------------- |
| `value`   | `*`  | Any value to pass to the handler |

**Returns:** the return value from the connected handler, or `null` if no handler is connected.

***

**`latch.destroy()`**

Destroys the latch, releasing any waiting threads (they will receive `null`). The latch becomes unusable.

**Returns:** `void`

***

**`latch.invoked` (property)**

A boolean that is `true` if `latch.invoke()` has been called at least once, `false` otherwise.

***

#### Latch Example

**Waiting for a result**

```javascript
const latch = task.latch()

task.thread(() => {
    // Simulate async work
    task.wait(2)
    latch.invoke("Done")
})

const result = latch.wait()
player.sendMessage("Result: " + result)
```

**Listening for multiple updates**

```javascript
const counter = task.latch()
let count = 0

counter.listen(value => {
    player.sendMessage("New count: " + value)
})

task.repeat(0, 5, () => {
    counter.invoke(++count)
})
```

***

## `delay()`

Executes a function after a delay asynchronously.

```js
task.delay(10, function() {
    log.info("Executed after 10 seconds")
})
```

**Parameters:**

* `delay` *(Number)*\
  Delay in seconds.
* `function` *(Function)*\
  Function to execute.

**Returns:**

* `taskId` *(Number)*

***

## `repeat()`

Runs a repeating task asynchronously .

```js
task.repeat(5, 20, function() {
    log.info("Repeating")
})
```

**Parameters:**

* `delay` *(Number)*\
  Initial delay in seconds.
* `period` *(Number)*\
  Repeat interval in ticks.
* `function` *(Function)*\
  Function to run.

**Returns:**

* `taskId` *(Number)*

***

## `cancel()`

Cancels a scheduled task.

```js
task.cancel(taskId)
```

**Parameters:**

* `taskId` *(Number)*\
  The task identifier.

***

## `bindToUnload()`

Registers a function to be executed when the script unloads.

```js
task.bindToUnload(function() {
    log.info("Cleanup complete")
})
```

**Parameters:**

* `function` *(Function)*\
  Cleanup handler.

***

## `wait()`

Pauses execution of the current script for a given number of seconds.

```js
task.wait(3)
```

**Parameters:**

* `seconds` *(Number)*\
  Time to wait in seconds.

**Returns:**

* `Boolean`\
  Returns `true` when completed. Throws if interrupted.

***

## `waitForScript()`

Blocks execution until specified script finishes loading.

```js
task.waitForScript("otherScript.js")
```

**Parameters:**

* `scriptName` *(String)*\
  Name of the script to wait for.

***

## `waitForPlugin()`

Blocks execution until a plugin becomes available.

```js
task.waitForPlugin("Vault")
```

**Parameters:**

* `pluginName` *(String)*\
  Name of the plugin.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://openjs.wiki.gd/apis-and-tools/globals/task.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
