Background Tasks
Tasks
Tasks are functions that run in the background. They're started when the application connects:
| Background Tasks Python Example |
|---|
| from kelvin.application import KelvinApp
import asyncio
app = KelvinApp()
@app.task
async def background_task():
"""Runs once when the app starts"""
print("Task started")
# Perform initialization or one-time operations
@app.task
async def continuous_task():
"""Runs continuously in the background"""
while True:
print("Processing...")
await asyncio.sleep(10)
# Can also register functions directly
async def another_task():
print("Another task")
app.task(another_task, name="my_task")
app.run()
|
Timers
Timers execute functions at regular intervals:
| Background Timers Python Example |
|---|
| from kelvin.application import KelvinApp
app = KelvinApp()
@app.timer(interval=30) # seconds
async def periodic_check():
"""Runs every 30 seconds"""
print("Periodic check executed")
@app.timer(interval=60)
async def publish_metrics():
"""Runs every 60 seconds"""
# Publish periodic metrics
await app.publish(...)
# Register timers directly
def sync_timer():
print("Sync timer")
app.timer(sync_timer, interval=10, name="sync_timer")
app.run()
|