scheduler-example.md 3.2 KB


title: Background scheduler group: Guides order: 10

summary: A WebApp that registers and runs a scheduled task.

A typical webapp has three files that work together to set up a background task.

./web/MyApp/backend.agi — called from the frontend via ao_module_agirun:

requirelib("scheduler");

var APP  = "MyApp";           // matches ./web/MyApp/
var TASK = "MyApp_HourlySync";

var action = getPara("action");

if (action === "status") {
    // Report current scheduler state and persisted stats
    var TABLE = "MyApp/" + USERNAME;
    newDBTableIfNotExists(TABLE);
    var lastRun  = readDBItem(TABLE, "lastRun");
    var runCount = parseInt(readDBItem(TABLE, "runCount") || "0", 10);
    sendJSONResp({
        hasPermission: scheduler.hasPermission(),
        registered:    scheduler.registered(TASK, APP),
        lastRun:       lastRun  || null,
        runCount:      runCount
    });

} else if (action === "register") {
    if (!scheduler.hasPermission()) {
        sendResp("no_permission");
    } else if (scheduler.registered(TASK, APP)) {
        sendResp("already_registered");
    } else {
        var ok = scheduler.register(TASK, APP, 3600, "Hourly sync for MyApp");
        sendResp(ok ? "ok" : "error");
    }

} else if (action === "unregister") {
    scheduler.unregister(TASK);
    sendOK();

} else {
    sendJSONResp({error: "unknown action"});
}

./web/MyApp/cron.agi — executed by the scheduler at each interval:

// Runs with the permissions of the user who approved the task.
// USERNAME, EXECUTION_ID and all standard globals are available.

var TABLE = "MyApp/" + USERNAME;
newDBTableIfNotExists(TABLE);

// Persist a timestamp and run counter for the frontend to display
writeDBItem(TABLE, "lastRun", new Date().toISOString());
var count = parseInt(readDBItem(TABLE, "runCount") || "0", 10);
writeDBItem(TABLE, "runCount", String(count + 1));

// EXECUTION_ID is a UUIDv4 unique to this invocation — appears in scheduler logs
console.log("MyApp tick [" + EXECUTION_ID + "] user=" + USERNAME + " run=" + (count + 1));

sendOK();

./web/MyApp/index.html — frontend snippet that requests permission and polls stats:

<script src="../script/ao_module.js"></script>
<script>
var APP  = "MyApp";
var TASK = "MyApp_HourlySync";

function checkStatus() {
    ao_module_agirun("MyApp/backend.agi", {action: "status"}, function(data) {
        document.getElementById('last-run').textContent =
            data.lastRun ? new Date(data.lastRun).toLocaleString() : "Never";
        document.getElementById('run-count').textContent = data.runCount;
        if (!data.registered && data.hasPermission) {
            document.getElementById('btn-enable').style.display = '';
        }
    });
}

function enableScheduler() {
    ao_module_requestSchedulerPermission({
        appName:     APP,
        appIcon:     APP + "/img/icon.png",
        taskName:    TASK,
        scriptName:  "cron.agi",   // filename inside ./web/MyApp/
        interval:    3600,         // seconds
        description: "Hourly sync for MyApp."
    }, function(result) {
        if (result && result.allowed) checkStatus();
    });
}

checkStatus();
setInterval(checkStatus, 30000);
</script>