|
1
|
# Custom scheduled jobs |
|
2
|
|
|
3
|
A scheduled job is a function executed at a specified interval of time in the background of your Medusa application. |
|
4
|
|
|
5
|
A scheduled job is created in a TypeScript or JavaScript file under the `src/jobs` directory. |
|
6
|
|
|
7
|
For example, create the file `src/jobs/hello-world.ts` with the following content: |
|
8
|
|
|
9
|
```ts |
|
10
|
import { |
|
11
|
MedusaContainer |
|
12
|
} from "@medusajs/framework/types"; |
|
13
|
|
|
14
|
export default async function myCustomJob(container: MedusaContainer) { |
|
15
|
const productService = container.resolve("product") |
|
16
|
|
|
17
|
const products = await productService.listAndCountProducts(); |
|
18
|
|
|
19
|
// Do something with the products |
|
20
|
} |
|
21
|
|
|
22
|
export const config = { |
|
23
|
name: "daily-product-report", |
|
24
|
schedule: "0 0 * * *", // Every day at midnight |
|
25
|
}; |
|
26
|
``` |
|
27
|
|
|
28
|
A scheduled job file must export: |
|
29
|
|
|
30
|
- The function to be executed whenever it’s time to run the scheduled job. |
|
31
|
- A configuration object defining the job. It has three properties: |
|
32
|
- `name`: a unique name for the job. |
|
33
|
- `schedule`: a [cron expression](https://crontab.guru/). |
|
34
|
- `numberOfExecutions`: an optional integer, specifying how many times the job will execute before being removed |
|
35
|
|
|
36
|
The `handler` is a function that accepts one parameter, `container`, which is a `MedusaContainer` instance used to resolve services. |