import ballerina/io;
import ballerina/task;
import ballerina/math;int count;function main (string[] args) {
    io:println("Timer task demo");
    function () returns (error|()) onTriggerFunction = cleanup;
    function (error e) onErrorFunction = cleanupError;
    string taskId = task:scheduleTimer(onTriggerFunction, onErrorFunction, {delay:500, interval:1000});
    io:println("Task ID:" + taskId);
}function cleanup () returns (error|()) {
    count = count + 1;
    io:println("Cleaning up...");
    io:println(count);
    if (math:randomInRange(0, 10) == 5) {
        error e = {message:"Cleanup error"};
        return e;
    }
    return ();
}function cleanupError (error e) {
    io:print("[ERROR] cleanup failed");
    io:println(e);
}

Task Timer

Timers are used to execute tasks periodically. A timer may have an initial delay & interval specified. The delay specifies the delay between registering the task and its first execution. Thereafter, the timer will go off at regular intervals. A trigger function is called when the timer goes off. If a failure occurs during the execution of the trigger function, it will return an error. That error will be passed to the onError function.

import ballerina/io;
import ballerina/task;
import ballerina/math;
int count;
function main (string[] args) {
    io:println("Timer task demo");
    function () returns (error|()) onTriggerFunction = cleanup;

the cleanup function will be called every time the timer goes off.

    function (error e) onErrorFunction = cleanupError;

the cleanup error function will be called if an error occurs while cleaning up.

    string taskId = task:scheduleTimer(onTriggerFunction, onErrorFunction, {delay:500, interval:1000});
    io:println("Task ID:" + taskId);
}

Schedule a timer task which initially runs 500ms from now and there onwards runs every 1000ms.

function cleanup () returns (error|()) {
    count = count + 1;
    io:println("Cleaning up...");
    io:println(count);
    if (math:randomInRange(0, 10) == 5) {
        error e = {message:"Cleanup error"};
        return e;
    }
    return ();
}

We randomly return an error to demonstrate how the error is propagated to the onError function when an error occurs in the onTrigger function.

function cleanupError (error e) {
    io:print("[ERROR] cleanup failed");
    io:println(e);
}
$ ballerina run task-timer.bal
Timer task demo
Task ID:ff6c2d4f-d9c2-46f4-a176-306d31fd2830
Cleaning up...
1
Cleaning up...
2
Cleaning up...
3
Cleaning up...
4
...
...