mirror of
https://github.com/supabase/supabase.git
synced 2026-10-17 23:29:08 +03:00
51 lines
1.8 KiB
Plaintext
51 lines
1.8 KiB
Plaintext
---
|
|
id: 'function-background-tasks'
|
|
title: 'Background Tasks'
|
|
description: 'How to run background tasks in an Edge Function outside of the request handler'
|
|
subtitle: 'How to run background tasks in an Edge Function outside of the request handler'
|
|
---
|
|
|
|
Edge Function instances can process background tasks outside of the request handler. Background tasks are useful for asynchronous operations like uploading a file to Storage, updating a database, or sending events to a logging service. You can respond to the request immediately and leave the task running in the background.
|
|
|
|
A background task can run until the Edge Function instance hits its [wall-clock limit](/docs/guides/functions/limits).
|
|
|
|
Here's an example of defining a background task using a custom event.
|
|
|
|
```ts
|
|
// define a custom event
|
|
class MyBackgroundTaskEvent extends Event {
|
|
readonly taskPromise: Promise<string>
|
|
|
|
constructor(taskPromise) {
|
|
super('myBackgroundTask')
|
|
this.taskPromise = taskPromise
|
|
}
|
|
}
|
|
|
|
globalThis.addEventListener('myBackgroundTask', async (event: MyBackgroundTaskEvent) => {
|
|
const res = await event.taskPromise
|
|
console.log(await res.json())
|
|
})
|
|
|
|
Deno.serve(async (req) => {
|
|
const fetchPromise = fetch('https://httpbin.org/json')
|
|
const event = new MyBackgroundTaskEvent(fetchPromise)
|
|
globalThis.dispatchEvent(event)
|
|
|
|
return new Response('ok')
|
|
})
|
|
```
|
|
|
|
### Testing background tasks locally
|
|
|
|
When testing Edge Functions locally with Supabase CLI, the instances are terminated automatically after a request is completed. This will prevent background tasks from running to completion.
|
|
|
|
To prevent that, you can update the `supabase/config.toml` with the following settings:
|
|
|
|
```toml
|
|
[edge_runtime]
|
|
policy = "per_worker"
|
|
```
|
|
|
|
When running with `per_worker` policy, Function won't auto-reload on edits. You will need to manually restart it by running `supabase functions serve`.
|