Coroutines

Take advantage of coroutines for a huge amount of flexibility when it comes to managing Elements' API functionality.

Coroutines are an integral part of cloud functions in Elements. Every invoked function (even in endpoints) is a coroutine, which allows for a tremendous amount of flexibility.

There are two ways to control coroutines in Elements:

-- The native Lua coroutine module

local coroutine = require "coroutine"

-- Helper class for gathering info and controlling 
-- coroutines from outside of the current coroutine

local namazu_coroutine = require "namazu.coroutine"

coroutine

In this example, we can use the native coroutine module to yield the current coroutine with a variety of commands.

Indicates the coroutine should yield and be rescheduled as soon as absolutely possible:

IMMEDIATE

Indicates that the coroutine should yield and be rescheduled until the provided absolute time. The time is expressed in the time since the unix epoch: January 1, 1970. The units may be specified, but the default value is in seconds:

UNTIL_TIME

Indicates that the should parse the second argument as a cron string. The coroutine will resume when at the next time the cron expression will hold true:

UNTIL_NEXT

Indicates that the coroutine should yield for the specified amount of time. The units may be specified, but the default is is in seconds:

Indicates that the coroutine should yield indefinitely. Typically this means the the calling code will manually resume the coroutine at some point later. Note that under some circumstances, the container may opt to forcibly kill the running Resource:

Indicates that the Resource should yield immediately just to save the state. This will not release the lock on the Resource and will ensure that the contents are written to disk before returning:

Valid time units that can be used for yielding are as follows:

For example:

namazu.coroutine

The namazu_coroutine provides three functions:

  • current_task_id()

  • start(coroutine)

  • resume(task_id)

Knowing the current task id is useful primarily for managing the state of the task externally. For example:

Sometimes, you might want to run several tasks asynchronously. To do this, you can create any number of other coroutines. Take this endpoint code for example:

Last updated