Background Jobs
Gravity supports background jobs with Bull.js. These are used for offloading longer tasks to a separate process.
You will need to set up a Redis database for tracking the job queue and then add the URL to the following environment variable:
REDIS_JOB_URL=
Run the following command to start the background worker:
node worker
The worker will process jobs added to the queue.
There's also a Procfile included to automatically start a separate worker dyno on Heroku. Other platforms will vary in how you set this up.
The default worker has a setTimeout function in worker/index.js – you should replace this with your own job function.
There are two ways to add a job to the queue in Gravity:
- 1.Internally
- 2.Using the API
To add a job on the server, use the following code:
const Queue = require('bull');
const jobQueue = new Queue('jobs', process.env.REDIS_JOB_URL);
async function addJob(){
const job = await jobQueue.add({ /* your custom metadata here */ });
}
To add a job via the API you can make a POST request to:
POST /api/job
It's helpful to set different statuses during the lifecycle of the job:
const job = await jobQueue.getJob(id);
job.progress('started');
If you want to update the job metadata you can make a PATCH request to:
PATCH /api/job/:id
The request body will be merged with the existing job data.
Once a job has begun, you'll want to check it's status and perform an action when it has completed. To do this, make a GET request to:
GET /api/job/:id
You can determine if a job has finished using the finishedOn key.
You can also fetch a job internally without using the API with:
const job = await jobQueue.getJob(id);
If a job has already started, you can't delete it from the queue.
You can delete a job that hasn't executed yet using the the API:
DELETE /api/job/:id
or anywhere in your internal app:
const job = await jobQueue.getJob(req.params.id);
await job.remove();
Last modified 1mo ago