Tickers in AngelScript
import std.time;
import std.system;
void main() {
// Tickers use a similar mechanism to timers: a
// mechanism that triggers at regular intervals. Here we'll use a
// while loop to check if it's time to trigger the ticker
// every 500ms.
uint64 tickInterval = 500; // milliseconds
uint64 lastTick = getSystemTime();
bool done = false;
// Start a separate thread to handle the ticker
thread ticker = thread(function() {
while (!done) {
uint64 currentTime = getSystemTime();
if (currentTime - lastTick >= tickInterval) {
print("Tick at " + formatSystemTime(currentTime, "%Y-%m-%d %H:%M:%S"));
lastTick = currentTime;
}
sleep(1); // Sleep for 1ms to avoid busy-waiting
}
});
// Tickers can be stopped. Once a ticker
// is stopped it won't receive any more values.
// We'll stop ours after 1600ms.
sleep(1600);
done = true;
ticker.join();
print("Ticker stopped");
}
This AngelScript code demonstrates a similar concept to the Go ticker example. Here’s an explanation of the changes and adaptations:
We use the
std.time
andstd.system
modules for time-related functions.Instead of using channels, we use a separate thread to simulate the ticker behavior.
The ticker is implemented using a while loop that checks if the interval has passed since the last tick.
We use
getSystemTime()
to get the current time and compare it with the last tick time.The
sleep()
function is used to pause execution, both in the ticker loop (to avoid busy-waiting) and in the main thread (to simulate the 1600ms wait).Instead of using a channel to signal the ticker to stop, we use a boolean variable
done
.
When we run this program, the ticker should tick approximately 3 times before we stop it, similar to the original example.
$ angelscript tickers.as
Tick at 2023-06-01 10:00:00
Tick at 2023-06-01 10:00:00
Tick at 2023-06-01 10:00:01
Ticker stopped
Note that the exact timing and output format may vary depending on the AngelScript implementation and the system’s time representation.