{"name":"scheduled-job","title":"Scheduled job","description":"Runs every 15 minutes on the platform's schedule: fetches a URL, records the result in /data and shows recent runs.","runtime":"Python 3.11, standard library","size":"small","env":[{"name":"TARGET_URL","required":false,"description":"The URL each run fetches. Default https://example.com/."},{"name":"JOB_TOKEN","required":false,"description":"When set, a run started by hand (not by the schedule) needs Authorization: Bearer <JOB_TOKEN>."}],"tags":["cron","schedule","monitoring","jobs","python"],"next":"It runs POST /tick every 15 minutes (UTC). Run it now with curl -X POST {url}/tick, then open {url}/ to see the run. Set TARGET_URL (oa env set {slug} TARGET_URL=...) to check your own URL.","oa_json":{"type":"service","start":"python3 job.py","sleep_after_s":60,"schedules":[{"cron":"*/15 * * * *","path":"/tick"}]},"files":[{"path":"README.md","content":"# Scheduled job\n\nA job the platform runs on a schedule: every 15 minutes it fetches a URL and\nrecords the status, the time it took, the size and a hash of the body (so a\nchange shows), and `GET /` lists the recent runs. Python with only the\nstandard library. Swap the fetch for your own work and keep the plumbing.\n\n## How the schedule works\n\nThe schedule is declared in `oa.json`:\n\n```json\n{\"type\": \"service\", \"start\": \"python3 job.py\", \"sleep_after_s\": 60,\n \"schedules\": [{\"cron\": \"*/15 * * * *\", \"path\": \"/tick\"}]}\n```\n\n`cron` is five fields, in UTC. At each tick the platform wakes the service and\nPOSTs to `path` with an `X-OA-Schedule` header. The platform strips `X-OA-*`\nheaders from every public request, so a request that carries one came from\nthe scheduler. Edit the cron line and republish to change the schedule; add\nentries to run several paths.\n\n## Call it\n\n```bash\ncurl -s -X POST <url>/tick            # run it now, by hand (trigger \"manual\")\ncurl -s <url>/                         # recent runs as JSON; a browser gets a table\ncurl -s \"<url>/runs?limit=50\"\n```\n\n## Environment\n\n| Variable | Required | What it does |\n| --- | --- | --- |\n| `TARGET_URL` | no | The URL each run fetches. Default `https://example.com/`. |\n| `JOB_TOKEN` | no | When set, a run started by hand needs `Authorization: Bearer <JOB_TOKEN>`. Scheduled runs never need it. |\n| `KEEP_RUNS` | no | How many runs to keep. Default 200. |\n\nSet them with `oa env set <slug> TARGET_URL=https://...` or\n`PUT /v1/artifacts/<slug>/env {\"env\":{\"TARGET_URL\":\"https://...\"}}`.\n\n## Data\n\nRuns are kept in `/data/runs.json`, a small file rewritten whole after every\nrun (to a sibling, then renamed over the old one), so it survives sleeps,\nrestarts and redeploys, and a crash mid-write leaves the previous list intact.\nRuns never overlap: a tick that arrives while one is running waits for it.\n\n## Extend it\n\n- Do your own work: replace the body of `run_job()` and return whatever you\n  want recorded. A run that raises is recorded as failed, not lost.\n- Alert on a change or a failure: `record[\"changed\"]` and `record[\"ok\"]` are\n  there; POST to a chat webhook from `run_job()` when they say so.\n- Keep a run short (well under the 60-second idle window), or the next request\n  waits for it.\n\n## What it costs\n\nPrices for `small`, the size this template needs (current prices on\n[openartifacts.sh](https://openartifacts.sh/#cost)):\n\n- **Asleep:** no runtime charge between ticks. The bundle and `/data` are stored at $0.05 per GB-month.\n- **Awake:** $0.03 per awake hour, billed per minute, plus $0.216 per vCPU-hour of CPU actually used. `sleep_after_s` is 60 here, so a short run keeps it awake about 65-70 seconds, billed as 2 minutes ($0.001): 96 ticks a day is about $0.10 a day, $2.88 a month, plus CPU.\n- Raising `sleep_after_s` or ticking more often raises that: at the default 600 seconds, a 15-minute schedule would keep it awake two thirds of the day, and a schedule more frequent than `sleep_after_s` keeps it awake for good ($0.72 a day).\n\nStarting it needs an hour of awake time in credit ($0.03), and an account runs\none service per $1 of balance.\n"},{"path":"job.py","content":"\"\"\"A job that runs on a schedule. Python standard library only.\n\n    POST /tick     run the job once (the platform calls this on schedule)\n    GET  /         the recent runs (HTML in a browser, JSON otherwise)\n    GET  /runs     the recent runs as JSON (?limit=20)\n\nThe schedule lives in oa.json (\"schedules\": [{\"cron\": \"*/15 * * * *\", \"path\":\n\"/tick\"}], UTC): at each tick the platform wakes the service and POSTs to the\npath with an X-OA-Schedule header. The platform strips X-OA-* headers from\npublic requests, so a request that carries one really came from the\nscheduler. The same POST works by hand (curl -X POST <url>/tick), which is how\nyou test it; set JOB_TOKEN to make hand-made runs need a bearer token.\n\nThe job itself: fetch TARGET_URL, record the status, the time it took, the\nsize and a hash of the body (so a change is visible), in /data/runs.json.\nThat file is small and rewritten whole after every run (written to a sibling,\nthen renamed over the old one), which is how files on /data should be written.\n\"\"\"\n\nimport hashlib\nimport hmac\nimport html\nimport json\nimport os\nimport sys\nimport threading\nimport time\nimport urllib.error\nimport urllib.request\nfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServer\nfrom urllib.parse import parse_qs, urlsplit\n\nPORT = int(os.environ.get(\"PORT\", \"8080\"))\nTARGET_URL = os.environ.get(\"TARGET_URL\", \"https://example.com/\")\n# Optional: when set, a run NOT started by the scheduler needs `Authorization: Bearer <JOB_TOKEN>`.\nJOB_TOKEN = os.environ.get(\"JOB_TOKEN\", \"\")\nDATA_DIR = os.environ.get(\"DATA_DIR\") or (\"/data\" if os.path.isdir(\"/data\") else os.path.join(os.getcwd(), \"data\"))\nRUNS_FILE = os.path.join(DATA_DIR, \"runs.json\")\nKEEP = int(os.environ.get(\"KEEP_RUNS\", \"200\"))\nTIMEOUT_S = 20\n\n\ndef load_runs():\n    try:\n        with open(RUNS_FILE) as f:\n            runs = json.load(f)\n        return runs if isinstance(runs, list) else []\n    except (FileNotFoundError, ValueError):\n        return []\n\n\ndef save_runs(runs):\n    os.makedirs(DATA_DIR, exist_ok=True)\n    tmp = RUNS_FILE + \".tmp\"\n    with open(tmp, \"w\") as f:\n        json.dump(runs, f)\n    os.replace(tmp, RUNS_FILE)\n\n\ndef schedules():\n    \"\"\"The schedule as oa.json declares it (the start command runs in the bundle's directory).\"\"\"\n    try:\n        with open(\"oa.json\") as f:\n            return json.load(f).get(\"schedules\") or []\n    except (FileNotFoundError, ValueError):\n        return []\n\n\nruns = load_runs()\n# One run at a time: a slow fetch must not overlap the next tick.\nrun_lock = threading.Lock()\n\n\ndef run_job(trigger, schedule):\n    \"\"\"The work. Replace the body of this function with your own job.\"\"\"\n    started = time.time()\n    record = {\n        \"at\": time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime(started)),\n        \"trigger\": trigger,\n        \"schedule\": schedule,\n        \"target\": TARGET_URL,\n    }\n    try:\n        request = urllib.request.Request(TARGET_URL, headers={\"user-agent\": \"openartifacts-scheduled-job/1\"})\n        with urllib.request.urlopen(request, timeout=TIMEOUT_S) as res:\n            body = res.read(5_000_000)\n            record.update(ok=200 <= res.status < 400, status=res.status, bytes=len(body),\n                          sha256=hashlib.sha256(body).hexdigest())\n    except urllib.error.HTTPError as err:\n        record.update(ok=False, status=err.code, error=f\"HTTP {err.code}\")\n    except Exception as err:  # DNS, timeout, refused: a failed run is still a run worth recording\n        record.update(ok=False, status=None, error=f\"{type(err).__name__}: {err}\")\n    record[\"ms\"] = round((time.time() - started) * 1000)\n    previous = next((r for r in reversed(runs) if r.get(\"sha256\")), None)\n    if record.get(\"sha256\"):\n        record[\"changed\"] = previous is not None and previous[\"sha256\"] != record[\"sha256\"]\n    return record\n\n\ndef page(recent):\n    rows = \"\".join(\n        f\"<tr><td>{html.escape(r['at'])}</td><td>{html.escape(r['trigger'])}</td>\"\n        f\"<td>{'ok' if r.get('ok') else 'failed'}</td><td>{r.get('status') or ''}</td>\"\n        f\"<td>{r.get('ms', '')} ms</td><td>{html.escape(r.get('error') or ('changed' if r.get('changed') else ''))}</td></tr>\"\n        for r in recent\n    ) or '<tr><td colspan=\"6\">No runs yet. The first scheduled tick will add one, or POST /tick now.</td></tr>'\n    cron = \", \".join(f\"{s.get('cron')} -> POST {s.get('path')}\" for s in schedules()) or \"none declared in oa.json\"\n    return f\"\"\"<!doctype html><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>scheduled-job</title>\n<style>body{{font:16px/1.5 Georgia,serif;max-width:46rem;margin:3rem auto;padding:0 1rem;color:#161616}}\ntable{{border-collapse:collapse;width:100%;font-size:15px}}td,th{{text-align:left;padding:.4rem .6rem .4rem 0;border-bottom:1px solid #e6e6e2}}\ncode{{background:#f7f7f4;padding:.1em .3em}}</style>\n<h1>scheduled-job</h1>\n<p>Fetches <code>{html.escape(TARGET_URL)}</code>. Schedule (UTC): <code>{html.escape(cron)}</code>.</p>\n<table><tr><th>When (UTC)</th><th>Trigger</th><th>Result</th><th>HTTP</th><th>Took</th><th>Note</th></tr>{rows}</table>\n<p>{len(runs)} runs recorded. JSON: <code>GET /runs</code>.</p>\"\"\"\n\n\nclass Handler(BaseHTTPRequestHandler):\n    server_version = \"scheduled-job/1\"\n\n    def send(self, status, body, content_type=\"application/json\"):\n        data = body.encode() if isinstance(body, str) else json.dumps(body).encode()\n        self.send_response(status)\n        self.send_header(\"content-type\", content_type)\n        self.send_header(\"content-length\", str(len(data)))\n        self.end_headers()\n        self.wfile.write(data)\n\n    def do_GET(self):\n        url = urlsplit(self.path)\n        path = url.path.rstrip(\"/\") or \"/\"\n        limit = max(1, min(int((parse_qs(url.query).get(\"limit\") or [\"20\"])[0] or 20), KEEP))\n        recent = runs[-limit:][::-1]\n        if path == \"/\" and \"text/html\" in self.headers.get(\"accept\", \"\"):\n            return self.send(200, page(recent), \"text/html; charset=utf-8\")\n        if path in (\"/\", \"/runs\"):\n            return self.send(200, {\n                \"job\": \"scheduled-job\",\n                \"target\": TARGET_URL,\n                \"schedules\": schedules(),\n                \"runs\": recent,\n                \"total\": len(runs),\n            })\n        self.send(404, {\"code\": \"not_found\", \"message\": f\"No route GET {path}. Try / or /runs.\"})\n\n    def do_POST(self):\n        path = urlsplit(self.path).path.rstrip(\"/\")\n        if path != \"/tick\":\n            return self.send(404, {\"code\": \"not_found\", \"message\": f\"No route POST {path}. The job runs on POST /tick.\"})\n        schedule = self.headers.get(\"x-oa-schedule\")\n        if schedule is None and JOB_TOKEN:\n            given = self.headers.get(\"authorization\", \"\")\n            if not hmac.compare_digest(given, f\"Bearer {JOB_TOKEN}\"):\n                return self.send(401, {\"code\": \"unauthorized\", \"message\": \"Send Authorization: Bearer <JOB_TOKEN> to run the job by hand.\"})\n        length = int(self.headers.get(\"content-length\") or 0)\n        if length:\n            self.rfile.read(min(length, 1_000_000))\n        global runs\n        with run_lock:\n            record = run_job(\"schedule\" if schedule is not None else \"manual\", schedule)\n            runs = (runs + [record])[-KEEP:]\n            save_runs(runs)\n        print(f\"run {record['trigger']}: {'ok' if record.get('ok') else 'failed'} {record.get('status')} in {record['ms']} ms\", flush=True)\n        self.send(200, record)\n\n    def log_message(self, fmt, *args):\n        sys.stderr.write(\"%s %s\\n\" % (self.address_string(), fmt % args))\n\n\nif __name__ == \"__main__\":\n    print(f\"scheduled-job listening on 0.0.0.0:{PORT}; target {TARGET_URL}; {len(runs)} runs on record\", flush=True)\n    server = ThreadingHTTPServer((\"0.0.0.0\", PORT), Handler)\n    server.daemon_threads = True\n    server.serve_forever()\n"},{"path":"oa.json","content":"{\n  \"type\": \"service\",\n  \"start\": \"python3 job.py\",\n  \"sleep_after_s\": 60,\n  \"schedules\": [{ \"cron\": \"*/15 * * * *\", \"path\": \"/tick\" }]\n}\n"}],"file_count":3,"bytes":11125,"page":"https://openartifacts.sh/templates/scheduled-job","publish":{"curl":"curl -sX POST https://openartifacts.sh/v1/publish -H \"Authorization: Bearer $OA_TOKEN\" -F type=service -F template=scheduled-job -F slug=my-job","mcp":{"tool":"publish_artifact","arguments":{"type":"service","template":"scheduled-job","slug":"my-job"}},"cli":"oa deploy --template scheduled-job --slug my-job"},"hint":"files is in the shape publish_artifact takes. To publish it unchanged: POST /v1/publish -F type=service -F template=scheduled-job. To publish an edited copy: send your changed files alongside -F template=scheduled-job (they replace the files of the same path), or publish the whole edited set without it (type=service; oa.json is among the files)."}