// retoor <retoor@molodetz.nl>
import "subprocess" for Popen
import "scheduler" for Scheduler
class AsyncPing {
construct new(host, label) {
_host = host
_label = label
_output = []
_done = false
}
start() {
_proc = Popen.new(["ping", "-c", "3", _host])
_fiber = Fiber.new {
while (true) {
var chunk = _proc.stdout.read()
if (chunk == "") {
_done = true
Fiber.yield()
return
}
for (line in chunk.split("\n")) {
if (line.trim() != "") _output.add(line)
}
Fiber.yield()
}
}
return this
}
tick() {
if (!_done && !_fiber.isDone) _fiber.call()
}
isDone { _done || _fiber.isDone }
label { _label }
output { _output }
host { _host }
}
System.print("=== Async Fiber Demo - 5 Concurrent Pings ===")
System.print("")
var tasks = [
AsyncPing.new("127.0.0.1", "LOCAL ").start(),
AsyncPing.new("8.8.8.8", "GOOGLE ").start(),
AsyncPing.new("1.1.1.1", "CLOUDFLR").start(),
AsyncPing.new("9.9.9.9", "QUAD9 ").start(),
AsyncPing.new("208.67.222.222", "OPENDNS ").start()
]
System.print("Started 5 async ping tasks:")
for (t in tasks) System.print(" [%(t.label)] -> %(t.host)")
System.print("")
while (true) {
var allDone = true
for (task in tasks) {
if (!task.isDone) {
allDone = false
var before = task.output.count
task.tick()
for (i in before...task.output.count) {
System.print("[%(task.label)] %(task.output[i])")
}
}
}
if (allDone) break
}
System.print("")
System.print("All 5 async tasks completed!")