Background Jobs
Last updated
Was this helpful?
Last updated
Was this helpful?
Gravity supports background jobs with . These are used for offloading longer tasks to a separate process. There is a working example included that manages an .
You will need to set up a Redis database for tracking the job queue and then add the URL to the following environment variable:
Run the following command to start the background worker:
The worker will process jobs added to the queue.
If you're using Mongo, the setup wizard will inject mongo.connect() into the worker. If you bypassed the setup wizard, you need to add this manually.
There's also a Procfile
included to start a separate worker dynos on automatically. 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:
Internally
Using the API
To add a job on the server, use the following code:
To add a job via the API, make a POST request to:
It's helpful to set different statuses during the lifecycle of the job:
If you want to update the job metadata, make a PATCH request to:
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:
You can determine if a job has finished using the finishedOn
key.
You can also fetch a job internally without using the API with:
If a job has already started, you can't delete it from the queue.
You can delete a job that hasn't been executed yet using the the API:
or anywhere in your internal app: