docs-site/content/docs/processing/task.md
+++ title = "Tasks" description = "" date = 2021-05-01T18:10:00+00:00 updated = 2021-05-01T18:10:00+00:00 draft = false weight = 4 sort_by = "weight" template = "docs/page.html"
[extra] lead = "" toc = true top = false flair =[] +++
Tasks in Loco serve as ad-hoc functionalities to handle specific aspects of your application. Whether you need to fix data, send emails, delete a user, or update a customer order, creating a dedicated task for each scenario provides a flexible and efficient solution. You can run tasks manually or by scheduling the task.
Creating tasks is worthwhile for several reasons:
Each task is designed to parse command-line arguments into flags, utilizing the yargs-parsed output of your CLI.
Loco provides a convenient code generator to simplify the creation of a starter task connected to your project. Use the following command to generate a task:
Generate the task:
<!-- <snip id="generate-task-help-command" inject_from="yaml" action="exec" template="sh"> -->Generate a Task based on the given name
Usage: demo_app-cli generate task [OPTIONS] <NAME>
Arguments:
<NAME> Name of the thing to generate
Options:
-e, --environment <ENVIRONMENT> Specify the environment [default: development]
-h, --help Print help
-V, --version Print version
Execute the task you created in the previous step using the following command:
<!-- <snip id="run-task-command" inject_from="yaml" template="sh"> -->cargo loco task <TASK_NAME>
To pass parameters to a task, add a list of key:value to the command
[PARAMS]... Task params (e.g. <`my_task`> foo:bar baz:qux)`
cargo loco task <TASK_NAME> [PARAMS]...
Then use that value using cli_arg in the run method of the task
async fn run(&self, app_context: &AppContext, vars: &task::Vars) -> Result<()> {
let foo = vars.cli_arg("foo");
Ok(())
}
To view a list of all tasks that have been executed, use the following command:
<!-- <snip id="list-tasks-command" inject_from="yaml" template="sh"> -->cargo loco task
If you prefer a manual approach to creating tasks in Loco, you can follow these steps:
Start by creating a new file under the path src/tasks. For example, let's create a file named example.rs:
use loco_rs::prelude::*;
pub struct Foo;
#[async_trait]
impl Task for Foo {
fn task(&self) -> TaskInfo {
TaskInfo {
name: "foo".to_string(),
detail: "run foo task".to_string(),
}
}
async fn run(&self, _app_context: &AppContext, _vars: &task::Vars) -> Result<()> {
Ok(())
}
}
Next, ensure that you load the newly created task file in the mod.rs file within the src/tasks folder.
In your App hook implementation (e.g., App struct), register the task in the register_tasks function:
// src/app.rs
pub struct App;
#[async_trait]
impl Hooks for App {
...
fn register_tasks(tasks: &mut Tasks) {
tasks.register(tasks::example::ExampleTask);
}
...
}
These steps ensure that your manually created task, such as ExampleTask, is integrated into Loco's task management system.