Skip to content

Latest commit

 

History

History
324 lines (269 loc) · 9.7 KB

usage-examples.md

File metadata and controls

324 lines (269 loc) · 9.7 KB

Usage Examples

This section provides practical examples of using fib-flow in different scenarios.

Table of Contents

Async Task Examples

Async tasks are one-time operations that can be scheduled to run immediately or with a delay. These tasks are perfect for handling background operations that don't require periodic execution.

Basic Task

The simplest form of async task execution. Use this when you need to process a task immediately in the background.

taskManager.async('processOrder', {
    orderId: '12345',
    userId: 'user789'
});

This example demonstrates processing an order asynchronously, which is ideal for tasks that shouldn't block the main execution flow.

Delayed Task

Delayed tasks are useful when you need to schedule a task to run after a specific time interval.

taskManager.async('sendReminder', {
    userId: 'user123',
    message: 'Don\'t forget to complete your profile!'
}, {
    delay: 3600  // Send reminder after 1 hour
});

Perfect for scenarios like sending follow-up reminders or scheduling delayed notifications.

Priority Task

When certain tasks need to be processed before others, you can assign them a priority level.

taskManager.async('sendNotification', {
    userId: 'user456',
    type: 'urgent',
    message: 'System alert!'
}, {
    priority: 10  // Higher priority task
});

Higher priority values ensure the task gets processed sooner in the queue.

Cron Task Examples

Cron tasks are recurring operations that follow a specified schedule. They're ideal for maintenance tasks and periodic operations.

Daily Task

Tasks that need to run once every day at a specific time.

taskManager.cron('dailyReport', '0 0 * * *', {
    reportType: 'daily',
    recipients: ['admin@example.com']
});

This example shows how to schedule a daily report generation at midnight.

Weekly Task

For operations that need to run once a week.

taskManager.cron('weeklyBackup', '0 0 * * 0', {
    backupType: 'full',
    destination: '/backups'
}, {
    timeout: 3600  // Allow up to 1 hour for backup
});

This task runs every Sunday at midnight and includes a timeout configuration for longer-running operations.

Monthly Task

Tasks that execute once per month.

taskManager.cron('monthlyCleanup', '0 0 1 * *', {
    older_than: '30d',
    target_dir: '/tmp'
}, {
    max_retries: 5,        // Maximum 5 total attempts
    retry_interval: 600
});

This example demonstrates a monthly cleanup task with retry logic for improved reliability.

Scheduled Work With Independent Runs (spawn mode)

By default a cron row runs the handler itself, which means the schedule and the run share one row: the round's result overwrites the previous one, and a handler that suspends freezes the whole schedule. Set cronMode: 'spawn' when you need every round to be its own task — so a run can suspend, retry, be audited and be collected independently.

const taskManager = new TaskManager({
    dbConnection: 'sqlite:jobs.db',
    cronMode: 'spawn'
});

taskManager.use('refreshCatalog', async (task) => {
    // One async row per round. task.payload is the schedule payload, verbatim.
    return refresh(task.payload.scope);
});

// The schedule row stores exactly the payload the handler expects.
taskManager.cron('refreshCatalog', '*/10 * * * *', { scope: 'all' });

taskManager.start();

// The schedule row stays 'pending' forever; runs come and go independently.
const [schedule] = taskManager.getCronSchedules({ name: 'refreshCatalog' });
console.log(schedule.status);                 // 'pending'
console.log(schedule.next_run_time);          // advances every round

// Runs are ordinary async tasks: filter by type.
const runs = taskManager.getTasks({ name: 'refreshCatalog', type: 'async' });
console.log(runs.length, runs[0].status);

// Which run belongs to the latest round?
console.log(schedule.last_spawned_task_id);

// Fire one extra round now, without moving next_run_time.
taskManager.runCronNow(schedule.id);

A handler that waits for a human no longer stops the clock:

taskManager.use('publishDigest', (task) => {
    if (task.stage === 0) {
        // This run parks here; the schedule keeps ticking.
        return task.suspend({ reason: 'awaiting_approval' });
    }
    return publish(task.payload);
});

taskManager.cron('publishDigest', '0 9 * * *', { channel: 'digest' });

Workflow Examples

Simple Workflow

A simple workflow executes tasks in a sequential manner:

// Define a simple linear workflow
taskManager.use('orderProcessing', (task, next) => {
    if (task.stage === 0) {
        // First validate the order
        return next({
            name: 'validateOrder',
            payload: { orderId: task.payload.orderId }
        });
    } else if (task.stage === 1) {
        // Then process payment
        return next({
            name: 'processPayment',
            payload: { orderId: task.payload.orderId }
        });
    }
    
    // Finally return the result
    return { status: 'completed' };
});

// Execute the workflow
taskManager.async('orderProcessing', { orderId: '123' });

This example shows a linear workflow where tasks are executed one after another.

Error Handling and Retry

Handling errors and retrying tasks:

taskManager.async('taskWithRetry', {
    taskData: { /* ... */ }
}, {
    retries: 3,
    retryDelay: 5000  // Retry every 5 seconds
});

This example demonstrates how to handle errors and retry tasks.

Task Control

Controlling task execution:

const taskId = taskManager.async('longRunningTask', { /* ... */ });

// Pause the task
taskManager.pauseTask(taskId);

// Resume the task
taskManager.resumeTask(taskId);

This example shows how to pause and resume tasks.

Nested Tasks

Nested tasks allow you to create complex hierarchical task structures where parent tasks can spawn and manage multiple child tasks:

// Define child tasks
taskManager.use('validateInventory', task => {
    return { result: 'inventory_validated' };
});

taskManager.use('processShipment', task => {
    return { result: 'shipment_processed' };
});

taskManager.use('sendNotifications', (task, next) => {
    if (task.stage === 0) {
        // Spawn multiple notification tasks in parallel
        return next([
            {
                name: 'sendSingleNotification',
                payload: { type: 'customer', orderId: task.payload.orderId }
            },
            {
                name: 'sendSingleNotification',
                payload: { type: 'warehouse', orderId: task.payload.orderId }
            }
        ]);
    }
    return { result: 'notifications_sent' };
});

// Define parent task that coordinates multiple child tasks
taskManager.use('fulfillOrder', (task, next) => {
    if (task.stage === 0) {
        // Run inventory check first
        return next({ 
            name: 'validateInventory', 
            payload: { items: task.payload.items } 
        });
    } else if (task.stage === 1) {
        // Then process shipment and notifications in parallel
        return next([
            { 
                name: 'processShipment', 
                payload: { 
                    items: task.payload.items,
                    address: task.payload.shippingAddress 
                } 
            },
            { 
                name: 'sendNotifications', 
                payload: { orderId: task.payload.orderId } 
            }
        ]);
    }
    
    // Finally return the result
    return { result: 'order_fulfilled' };
});

This example shows how nested tasks can create complex workflows with parallel execution and task hierarchies.

Task Tagging and Statistics

Tags provide a way to categorize and track tasks across your system. You can use tags to organize tasks by feature, environment, customer, or any other dimension.

Adding Tags to Tasks

// Add tag to async task
taskManager.async('processOrder', {
    orderId: '12345'
}, {
    tag: 'orders'  // Tag for order processing tasks
});

// Add tag to cron task
taskManager.cron('dailyReport', '0 0 * * *', {
    reportType: 'sales'
}, {
    tag: 'reports'  // Tag for reporting tasks
});

Querying Tasks by Tag

// Get all tasks with a specific tag
const orderTasks = taskManager.getTasksByTag('orders');
console.log('Order tasks:', orderTasks.length);

// Get task statistics by tag
const stats = taskManager.getTaskStatsByTag('orders');
console.log('Order task statistics:', stats);
// Example output:
// [
//   { tag: 'orders', name: 'processOrder', status: 'pending', count: 5 },
//   { tag: 'orders', name: 'processOrder', status: 'completed', count: 10 }
// ]

// Get statistics for completed tasks only
const completedStats = taskManager.getTaskStatsByTag('orders', 'completed');
console.log('Completed orders:', completedStats);

Common Use Cases for Tags

  • Track tasks by feature or service
  • Monitor tasks by customer or tenant
  • Separate tasks by environment (dev/staging/prod)
  • Group related tasks in a workflow
  • Track tasks by priority or importance