> ## Documentation Index
> Fetch the complete documentation index at: https://docs.magmadeploy.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Jobs

> Add scheduled tasks to your Magma agents

## Overview

Jobs in Magma allow you to schedule recurring tasks for your agent to perform. Using the `@job` decorator, you can define tasks that run on a specified schedule using cron syntax.

<Info>
  If a job is not declared as static, it will be scheduled to run on the agent's instance, for every session of the agent. Learn more about [sessions](/magma-framework/sessions)
</Info>

## Basic Implementation

Here's a simple example of implementing a job:

```typescript theme={null}
import { MagmaAgent } from "@pompeii-labs/magma";
import { job } from "@pompeii-labs/magma/decorators";

class MyAgent extends MagmaAgent {
    @job("0 0 * * *") // Runs daily at midnight
    async dailyBackup() {
        const result = await this.backupData();
        console.log(`Backup completed: ${result}`);
    }
}
```

***

## Job Scheduling

Jobs use standard cron syntax for scheduling:

```typescript theme={null}
@job("* * * * *")      // Every minute
@job("0 * * * *")      // Every hour
@job("0 0 * * *")      // Every day at midnight
@job("0 0 * * 0")      // Every Sunday at midnight
@job("0 0 1 * *")      // First day of every month
```

You can learn more about cron syntax [here](https://www.npmjs.com/package/node-cron#cron-syntax), and you can use the [Cron Editor](https://crontab.guru/) to help you create the correct syntax.

***

## Advanced Job Configuration

Jobs can accept configuration options:

```typescript theme={null}
@job("0 0 * * *", {
    timezone: "America/New_York",
})
async complexJob() {
    // Implementation here
}
```

***

## Static Jobs

Some jobs don't need to access the agent's context, and don't need to be run on every session of the agent. You can declare them as static methods:

```typescript theme={null}
@job("0 0 * * *")
static async dailyBackup() {
    const result = await this.backupData();
    console.log(`Backup completed: ${result}`);
}
```

This job will be handled without instantiating the agent.

***

## Common Use Cases

### Data Synchronization

```typescript theme={null}
class MyAgent extends MagmaAgent {
    @job("*/15 * * * *") // Every 15 minutes
    async syncData() {
        const updates = await this.fetchExternalData();
        await this.updateLocalDatabase(updates);
        console.log(`Synced ${updates.length} records`);
    }
}
```

### Maintenance Tasks

```typescript theme={null}
class MyAgent extends MagmaAgent {
    @job("0 0 * * 0") // Weekly on Sunday
    async weeklyCleanup() {
        await this.cleanTempFiles();
        await this.optimizeDatabase();
        console.log("Weekly maintenance completed");
    }
}
```

### Report Generation

```typescript theme={null}
class MyAgent extends MagmaAgent {
    @job("0 9 * * 1-5") // Weekdays at 9 AM
    async generateDailyReport() {
        const report = await this.compileMetrics();
        await this.emailReport(report);
        console.log("Daily report sent");
    }
}
```

### Agent completions

```typescript theme={null}
class MyAgent extends MagmaAgent {
    @job("0 9 * * 1-5") // Weekdays at 9 AM
    async doAgentStuff() {
        const completion = await this.main();
        console.log(completion.content);
    }
}
```

<Warning>
  Use caution when using the `main` method in a job. You should only use it if your agent will not be conducting conversations
</Warning>

***

## Best Practices

1. **Error Handling**
   ```typescript theme={null}
   @job("0 * * * *")
   async hourlyTask() {
       try {
           const result = await this.processData();
           console.log(`Task completed: ${result}`);
       } catch (error) {
           await this.notifyAdmin(error);
           throw new Error(`Task failed: ${error.message}`);
       }
   }
   ```

2. **Resource Management**
   * Consider server load during job scheduling
   * Avoid overlapping job executions that modify the same resources
   * Implement proper cleanup in case of failures

3. **Monitoring**
   * Log job execution results
   * Track execution time
   * Monitor success/failure rates

## Limitations

* Jobs must be async methods
* Maximum execution time is 5 minutes
* Timezone must be a valid IANA timezone string

<Tip>
  For long-running tasks, consider breaking them into smaller sub-tasks or using a queue-based approach.
</Tip>
