Mercurial > prosody-hg
comparison util/async.lua @ 11961:542a9a503073
util.async: Add sleep() method with configurable scheduling backend
No scheduler set by default, so it will error (we plan to initialize it in
util.startup).
We wanted to avoid a hard dependency on util.timer (which in turn depends on
network backends, etc.), and we didn't add timer.sleep() because we didn't
want to add a hard dependency on util.async for things that don't need it.
| author | Matthew Wild <mwild1@gmail.com> |
|---|---|
| date | Mon, 29 Nov 2021 14:11:24 +0000 |
| parents | 558f0555ba02 |
| children | 9a70a543c727 |
comparison
equal
deleted
inserted
replaced
| 11960:12a3c05aa12d | 11961:542a9a503073 |
|---|---|
| 8 if not thread or main then | 8 if not thread or main then |
| 9 error("Not running in an async context, see https://prosody.im/doc/developers/util/async"); | 9 error("Not running in an async context, see https://prosody.im/doc/developers/util/async"); |
| 10 end | 10 end |
| 11 return thread; | 11 return thread; |
| 12 end | 12 end |
| 13 | |
| 14 -- Configurable functions | |
| 15 local schedule_task = nil; -- schedule_task(seconds, callback) | |
| 13 | 16 |
| 14 local function runner_from_thread(thread) | 17 local function runner_from_thread(thread) |
| 15 local level = 0; | 18 local level = 0; |
| 16 -- Find the 'level' of the top-most function (0 == current level, 1 == caller, ...) | 19 -- Find the 'level' of the top-most function (0 == current level, 1 == caller, ...) |
| 17 while debug.getinfo(thread, level, "") do level = level + 1; end | 20 while debug.getinfo(thread, level, "") do level = level + 1; end |
| 114 exit(); | 117 exit(); |
| 115 return; | 118 return; |
| 116 end | 119 end |
| 117 return exit; | 120 return exit; |
| 118 end; | 121 end; |
| 122 end | |
| 123 | |
| 124 local function sleep(seconds) | |
| 125 if not schedule_task then | |
| 126 error("async.sleep() is not available - configure schedule function"); | |
| 127 end | |
| 128 local wait, done = waiter(); | |
| 129 schedule_task(seconds, done); | |
| 130 wait(); | |
| 119 end | 131 end |
| 120 | 132 |
| 121 local runner_mt = {}; | 133 local runner_mt = {}; |
| 122 runner_mt.__index = runner_mt; | 134 runner_mt.__index = runner_mt; |
| 123 | 135 |
| 270 waiter = waiter; | 282 waiter = waiter; |
| 271 guarder = guarder; | 283 guarder = guarder; |
| 272 runner = runner; | 284 runner = runner; |
| 273 wait = wait_for; -- COMPAT w/trunk pre-0.12 | 285 wait = wait_for; -- COMPAT w/trunk pre-0.12 |
| 274 wait_for = wait_for; | 286 wait_for = wait_for; |
| 287 sleep = sleep; | |
| 288 | |
| 289 set_schedule_function = function (new_schedule_function) schedule_task = new_schedule_function; end; | |
| 275 }; | 290 }; |
