Fang
Background job processing library for Rust.
Currently, it uses Postgres to store state. But in the future, more backends will be supported.
Installation
- Add this to your Cargo.toml
[]
= "0.3"
= "0.1"
= { = "1.0", = ["derive"] }
- Create
fang_taskstable in the Postgres database. The migration can be found in the migrations directory.
Usage
Defining a job
Every job should implement fang::Runnable trait which is used by fang to execute it.
use Error;
use Runnable;
use ;
As you can see from the example above, the trait implementation has #[typetag::serde] attribute which is used to deserialize the job.
Enqueuing a job
To enqueue a job use Postgres::enqueue_task
use Postgres;
...
enqueue_task.unwrap;
The example above creates a new postgres connection on every call. If you want to reuse the same postgres connection to enqueue several jobs use Postgres struct instance:
let postgres = new;
for id in &unsynced_feed_ids
Starting workers
Every worker runs in a separate thread. In case of panic, they are always restarted.
Use WorkerPool to start workers. WorkerPool::new accepts one parameter - the number of workers.
use WorkerPool;
new.start;
Configuration
To configure workers, instead of WorkerPool::new which uses default values, use WorkerPool.new_with_params. It accepts two parameters - the number of workers and WorkerParams struct.
Configuring the type of workers
You can start workers for a specific types of tasks. These workers will be executing only tasks of the specified type.
Add task_type method to the Runnable trait implementation:
...
Set task_type to the WorkerParamas:
let mut worker_params = WorkerParams::new();
worker_params.set_task_type("number".to_string());
WorkerPool::new_with_params(10, worker_params).start();
Without setting task_type workers will be executing any type of task.
Configuring retention mode
By default, all successfully finished tasks are removed from the DB, failed tasks aren't.
There are three retention modes you can use:
Set retention mode with set_retention_mode:
let mut worker_params = new;
worker_params.set_retention_mode;
new_with_params.start;
Configuring sleep values
You can use use SleepParams to confugure sleep values:
p
If there are no tasks in the DB, a worker sleeps for sleep_period and each time this value increases by sleep_step until it reaches max_sleep_period. min_sleep_period is the initial value for sleep_period. All values are in seconds.
Use set_sleep_params to set it:
let sleep_params = SleepParams ;
let mut worker_params = new;
worker_params.set_sleep_params;
new_with_params.start;
Potential/future features
- Retries
- Scheduled tasks
- Extendable/new backends
Contributing
- Fork it!
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request
Author
Ayrat Badykov (@ayrat555)