1# Worker
2
3**Process background jobs with a database-driven worker.**
4
5Jobs are defined using the `Job` base class and the `run()` method at a minimum.
6
7```python
8from plain.worker import Job, register_job
9from plain.email import send_mail
10
11
12@register_job
13class WelcomeUserJob(Job):
14 def __init__(self, user):
15 self.user = user
16
17 def run(self):
18 send_mail(
19 subject="Welcome!",
20 message=f"Hello from Plain, {self.user}",
21 from_email="[email protected]",
22 recipient_list=[self.user.email],
23 )
24```
25
26You can then create an instance of the job and call `run_in_worker()` to enqueue it for a background worker to pick up.
27
28```python
29user = User.objects.get(pk=1)
30WelcomeUserJob(user).run_in_worker()
31```
32
33Workers are run using the `plain worker run` command.
34
35## Installation
36
37Install `plain.worker` and add it to your `INSTALLED_PACKAGES`.
38
39```python
40# app/settings.py
41INSTALLED_PACKAGES = [
42 ...
43 "plain.worker",
44]
45```
46
47Jobs can be defined in any Python file, but it is suggested to use `app/jobs.py` or `app/{pkg}/jobs.py` as those will be imported automatically so the `@register_job` will fire.
48
49## Local development
50
51In development, you will typically want to run the worker alongside your app. With [`plain.dev`](/plain-dev/plain/dev/README.md) you can do this by adding it to the `[tool.plain.dev.run]` section of your `pyproject.toml` file. Currently, you will need to use something like [watchfiles](https://pypi.org/project/watchfiles/) to add auto-reloading to the worker.
52
53```toml
54# pyproject.toml
55[tool.plain.dev.run]
56worker = {cmd = "watchfiles --filter python \"plain worker run --stats-every 0 --max-processes 2\" ."}
57worker-slow = {cmd = "watchfiles --filter python \"plain worker run --queue slow --stats-every 0 --max-processes 2\" ."}
58```
59
60## Job parameters
61
62TODO
63
64## Admin
65
66TODO
67
68## Job history
69
70TODO
71
72## Scheduled jobs
73
74TODO
75
76## Monitoring
77
78TODO