TaskEvent

Enum TaskEvent 

Source
pub enum TaskEvent {
    Started {
        process_id: u32,
        created_at: SystemTime,
        running_at: SystemTime,
    },
    Output {
        line: String,
        src: StreamSource,
    },
    Ready,
    Stopped {
        exit_code: Option<i32>,
        reason: TaskStopReason,
        finished_at: SystemTime,
        signal: Option<Signal>,
    },
    Error {
        error: TaskError,
    },
    ProcessControl {
        action: ProcessControlAction,
    },
}
Expand description

Events emitted during task execution lifecycle

TaskEvent represents all events that occur during task execution, from process start to completion. These events enable real-time monitoring and event-driven programming patterns.

§Event Flow

A typical task execution emits events in this order:

  1. Started - Process has been spawned
  2. Output - Output lines from stdout/stderr (ongoing)
  3. Ready - Ready indicator detected (optional, for long-running processes)
  4. Stopped - Process has completed, with exit code and reason
    • Exit code is Some(code) for natural completion
    • Exit code is None for terminated processes (timeout, manual termination)
  5. Error - Error related to task execution

§Examples

§Basic Event Processing

use tcrm_task::tasks::{config::TaskConfig, tokio::executor::TaskExecutor, event::TaskEvent};
use tokio::sync::mpsc;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    #[cfg(windows)]
    let config = TaskConfig::new("cmd").args(["/C", "echo", "hello", "world"]);
    #[cfg(unix)]
    let config = TaskConfig::new("echo").args(["hello", "world"]);
     
    let (tx, mut rx) = mpsc::channel(100);
    let mut executor = TaskExecutor::new(config, tx);
     
    executor.coordinate_start().await?;

    while let Some(envelope) = rx.recv().await {
        match envelope.event {
            TaskEvent::Started { process_id, .. } => {
                println!("Process started with ID: {}", process_id);
            }
            TaskEvent::Output { line, .. } => {
                println!("Output: {}", line);
            }
            TaskEvent::Stopped { exit_code, .. } => {
                match exit_code {
                    Some(code) => println!("Process completed with code {}", code),
                    None => println!("Process was terminated"),
                }
                break;
            }
            TaskEvent::Error { error } => {
                eprintln!("Error: {}", error);
                break;
            }
            _ => {}
        }
    }

    Ok(())
}

§Server Ready Detection

use tcrm_task::tasks::{
    config::{TaskConfig, StreamSource},
    tokio::executor::TaskExecutor,
    event::TaskEvent
};
use tokio::sync::mpsc;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    #[cfg(windows)]
    let config = TaskConfig::new("cmd")
        .args(["/C", "echo", "Server listening"])
        .ready_indicator("Server listening")
        .ready_indicator_source(StreamSource::Stdout);
     
    #[cfg(unix)]
    let config = TaskConfig::new("echo")
        .args(["Server listening"])
        .ready_indicator("Server listening")
        .ready_indicator_source(StreamSource::Stdout);

    let (tx, mut rx) = mpsc::channel(100);
    let mut executor = TaskExecutor::new(config, tx);
    executor.coordinate_start().await?;

    while let Some(envelope) = rx.recv().await {
        match envelope.event {
            TaskEvent::Ready => {
                println!("Server is ready for requests!");
                // Server is now ready - can start sending requests
                break;
            }
            TaskEvent::Output { line, .. } => {
                println!("Server log: {}", line);
            }
            _ => {}
        }
    }

    Ok(())
}

Variants§

§

Started

Process has been successfully spawned and is running.

This is the first event emitted after successful process spawning. The process is now running and other events will follow.

§Fields

  • process_id - Operating system process ID of the spawned process
  • created_at - Timestamp when the process was created
  • running_at - Timestamp when the process started running

Fields

§process_id: u32

Operating system process ID of the spawned process

§created_at: SystemTime

Timestamp when the process was created

§running_at: SystemTime

Timestamp when the process started running

§

Output

Output line received from the process.

Emitted for each line of output from stdout or stderr. Lines are buffered and emitted when complete (on newline).

§Fields

  • line - The output line (without trailing newline)
  • src - Source stream (stdout or stderr)

Fields

§line: String

The output line (without trailing newline)

§src: StreamSource

Source stream (stdout or stderr)

§

Ready

task has signaled it’s ready to work.

Only emitted for long-running processes that have a ready indicator configured. Indicates the task has completed initialization and is ready for work (e.g., server is listening).

§

Stopped

Task has completed execution.

The task has exited and all resources have been cleaned up.

§Fields

  • exit_code - Exit code from the process
    • Some(code) - Process completed naturally with exit code
    • None - Process was terminated (timeout, user request, etc.)
  • reason - Reason the process stopped
  • finished_at - Timestamp when the process finished
  • signal (Unix only) - Termination signal if the process was killed by a signal

Fields

§exit_code: Option<i32>

Exit code from the process

  • Some(code) - Process completed naturally with exit code
  • None - Process was terminated (timeout, user request, etc.)

Note: Terminated processes do not provide exit codes to avoid race conditions between termination and natural completion.

§reason: TaskStopReason

Reason the process stopped

§finished_at: SystemTime

Timestamp when the process finished

§signal: Option<Signal>

Termination signal if the process was killed by a signal

§

Error

An error occurred during task execution.

Emitted when errors occur during configuration validation, process spawning, or input/output operations.

§Fields

  • error - The specific error that occurred

Fields

§error: TaskError

The specific error that occurred

§

ProcessControl

Process control action event.

Emitted when a process control action (pause, resume, stop) is performed on the running process.

§Fields

  • action - The process control action that was performed (pause, resume, stop)

Fields

§action: ProcessControlAction

The process control action that was performed (pause, resume, stop)

Trait Implementations§

Source§

impl Clone for TaskEvent

Source§

fn clone(&self) -> TaskEvent

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for TaskEvent

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for TaskEvent

Source§

fn eq(&self, other: &TaskEvent) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for TaskEvent

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.