---
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`:
```javascript
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:
```javascript
// 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:
```html
```