# 5. Your first cron job

### Overview

The Cron Job Manager is a powerful feature in ServerCompass that allows you to inspect, create, and manage scheduled tasks (cron jobs) on your remote servers. Instead of editing crontab files manually via SSH, you can manage all your scheduled tasks through an intuitive interface that applies changes directly to the remote server.

### What are Cron Jobs?

Cron jobs are scheduled tasks that run automatically at specified times or intervals on Unix-like systems. Common uses include:

* Automated backups
* Database maintenance
* Log rotation
* System monitoring
* Periodic data synchronization
* Automated deployments
* Report generation

### Getting Started

The Cron Job Manager appears on your server's detail page. When you open it, you'll see all scheduled tasks from both the current user's crontab and root's crontab (if accessible).

#### Interface Layout

The Cron Job Manager consists of:

* **Header**: Title, description, and action buttons
* **Job List**: Table showing all cron jobs with details
* **Job Editor**: Modal for creating or editing jobs
* **SSH Preview**: Shows the command to run manually if needed

### Viewing Cron Jobs

#### Understanding the Job List

Each cron job displays the following information:

**Job Metadata**

* **Name**: Custom label for the job (e.g., "Nightly Database Backup")
* **Description**: Optional details explaining the job's purpose
* **Owner Badge**: Shows whether it's a "user cron" or "root cron"
* **Type Badge**: Category of the job:
  * **System**: System-level tasks
  * **ServerCompass**: Jobs created by ServerCompass
  * **User**: User-created tasks
  * **Manual**: Manually added jobs
  * **Unknown**: Uncategorized jobs
* **Created By**: Shows who or what created the job
* **Status**: Active (green) or Paused (gray)

**Schedule Information**

* **Friendly Label**: Human-readable schedule (e.g., "Daily at midnight")
* **Cron Expression**: The actual cron syntax (e.g., `0 0 * * *`)
* Special schedules like `@daily`, `@hourly`, or `@reboot` are shown as macros

**Command**

The command or script that will be executed when the job runs.

#### Root vs User Cron Jobs

ServerCompass can display both types of cron jobs:

* **User Cron**: Jobs belonging to the connected SSH user
* **Root Cron**: System-level jobs (requires passwordless `sudo crontab` access)

If root jobs are detected, you'll see a purple notice explaining the sudo requirement.

### Creating New Cron Jobs

To create a new scheduled task:

1. Click the **New Cron Job** button
2. Fill in the job details:
   * **Command** (required): The script or command to run
   * **Job Name**: A descriptive label
   * **Description**: Optional context for your team
   * **Type**: Category (System, User, ServerCompass, etc.)
   * **Schedule**: Choose from presets or use custom expression
3. Click **Generate SSH Command**
4. Copy and run the provided SSH command in your terminal
5. Click **Refresh** to see the new job in the list

#### Best Practices for Commands

* Use **absolute paths** for scripts and executables
  * Good: `/usr/bin/bash /home/user/backup.sh`
  * Bad: `bash backup.sh`
* Redirect output if needed: `command > /var/log/output.log 2>&1`
* Ensure the script is executable: `chmod +x /path/to/script.sh`
* Test the command manually before scheduling it

#### Why SSH Command Generation?

When creating new jobs, ServerCompass generates an SSH command for you to run manually. This approach:

* Ensures you have proper permissions
* Allows you to review the exact cron entry being added
* Provides transparency in what's being executed on your server
* Works even if direct crontab manipulation encounters permission issues

After running the SSH command, refresh the cron job list to see your new entry.

### Schedule Presets

ServerCompass provides friendly schedule presets for common intervals:

#### Minute-Based

* **Every minute**: Runs continuously
* **Every 5 minutes**: `*/5 * * * *`
* **Every 10 minutes**: `*/10 * * * *`
* **Every 15 minutes**: `*/15 * * * *`
* **Every 30 minutes**: `*/30 * * * *`

#### Hour-Based

* **Every hour**: Runs at the start of each hour
* **Every 2 hours**: `0 */2 * * *`
* **Every 6 hours**: `0 */6 * * *`

#### Daily

* **Daily at midnight**: `0 0 * * *`
* **Daily at noon**: `0 12 * * *`

#### Weekly

* **Weekly on Monday**: Every Monday at midnight
* **Weekly on Sunday**: Every Sunday at midnight

#### Monthly

* **Monthly (1st day)**: First day of each month at midnight

#### Custom

* **Custom (Advanced)**: Define your own cron expression

### Editing Existing Jobs

To modify a cron job:

1. Click the **Edit** button next to the job
2. Update the fields you want to change:
   * **Name and Description**: Add or modify labels
   * **Type and Created By**: Update categorization
   * **Schedule**: Change when the job runs
   * **Active Status**: Enable or disable the job
3. Click **Save Changes** to apply

#### What Can Be Edited?

**For Standard Jobs**:

* Name, description, type, created by metadata
* Schedule (using presets or custom expressions)
* Active/inactive status

**For Macro Jobs** (like `@daily`):

* Name, description, type, created by metadata
* Active/inactive status
* Schedule **cannot** be edited through the UI (must use `crontab -e` manually)

#### Viewing SSH Commands for Edits

Click **View SSH command** in the editor to see the exact command that will be executed on your server. This helps you understand what changes are being made.

### Advanced Scheduling

For more complex schedules, use the **Advanced** mode:

1. Click **Advanced (edit cron expression)** in the schedule section
2. Enter values for each field:
   * **Minute**: 0-59
   * **Hour**: 0-23
   * **Day**: 1-31 (day of month)
   * **Month**: 1-12
   * **Weekday**: 0-7 (0 and 7 are Sunday)

#### Cron Expression Syntax

Each field accepts:

* **Numbers**: Specific values (e.g., `5` for 5 minutes)
* **Asterisk (`*`)**: Any value (e.g., `*` in minute means every minute)
* **Ranges**: `1-5` (Monday through Friday)
* **Lists**: `1,3,5` (Monday, Wednesday, Friday)
* **Step values**: `*/15` (every 15 units)
* **Combinations**: `0,30 9-17 * * 1-5` (9 AM to 5 PM on weekdays)

#### Examples

```
0 2 * * *        → Daily at 2:00 AM
*/15 * * * *     → Every 15 minutes
30 1 * * 1       → Mondays at 1:30 AM
0 0 1 * *        → First day of each month
0 9-17 * * 1-5   → Hourly from 9 AM to 5 PM on weekdays
0 */4 * * *      → Every 4 hours
```

The cron expression preview updates in real-time as you make changes.

### Managing Job Status

#### Pausing and Resuming Jobs

To temporarily disable a job without deleting it:

1. Click the **Pause** button next to an active job
2. The job status changes to "Paused" and won't execute
3. Click **Resume** to reactivate it

Paused jobs remain in the crontab but are commented out with a `#` prefix.

#### Active Status Indicator

Each job shows its current state:

* **Active** (green badge with play icon): Job is running on schedule
* **Paused** (gray badge with pause icon): Job exists but won't execute

### Deleting Cron Jobs

To permanently remove a scheduled task:

1. Click the **Delete** button next to the job
2. Confirm the deletion in the popup dialog
3. The job is removed from the crontab immediately

**Warning**: Deletion is permanent and cannot be undone. Make sure you have backups of important jobs.

### Job Metadata and Organization

#### Job Types

Categorize your cron jobs for better organization:

* **System**: Critical system tasks
* **User**: Personal or user-specific tasks
* **ServerCompass**: Jobs created by ServerCompass automation
* **Manual**: Manually added entries
* **Unknown**: Uncategorized (default for existing jobs)

#### Created By Field

Track job ownership with the "Created By" field:

* Defaults to `servercompass-ui` for new jobs
* Can be updated to indicate the person or process that created it
* Helps teams understand job origins

#### Descriptions

Add descriptions to explain:

* What the job does
* Why it's needed
* Dependencies or requirements
* Expected output or effects

Good descriptions help team members understand the purpose of each scheduled task.

### Working with Root Cron Jobs

Some system tasks require root privileges. If your server user has passwordless `sudo crontab` access, you can manage root cron jobs through ServerCompass.

#### Requirements

To manage root cron jobs, your SSH user must be able to run:

```bash
sudo crontab -l
sudo crontab -e
```

without entering a password.

#### Setting Up Passwordless Sudo

Add this to your `/etc/sudoers` file (use `visudo`):

```
username ALL=(ALL) NOPASSWD: /usr/bin/crontab
```

Replace `username` with your SSH username.

#### Root Job Indicator

Root cron jobs are clearly labeled with a purple "root cron" badge. All actions on these jobs will use `sudo crontab` commands.

### Troubleshooting

#### "Cron integration not available"

**Cause**: The cron IPC handlers aren't loaded in the renderer process.

**Solution**: Restart the ServerCompass desktop application. This error typically appears when running the web preview instead of the packaged Electron app.

#### "Unable to load cron jobs"

**Possible causes**:

* SSH connection is not active
* User doesn't have permission to read crontab
* Cron service is not running on the server

**Solutions**:

* Verify SSH connection is working
* Check if `crontab -l` works manually via terminal
* Ensure cron service is running: `sudo systemctl status cron`

#### Toggle or Delete Failed

**Possible causes**:

* Permission issues (especially for root jobs)
* SSH connection dropped
* Invalid crontab syntax

**Solutions**:

* For root jobs, verify passwordless sudo access
* Check SSH connection is stable
* Use the "View SSH command" feature to run commands manually

#### Job Not Executing

If a cron job shows as "Active" but doesn't run:

1. **Check the command works**: Run it manually via terminal
2. **Verify paths**: Use absolute paths for all files and scripts
3. **Check permissions**: Ensure scripts are executable
4. **Review cron logs**: Check `/var/log/syslog` or `/var/log/cron`
5. **Validate schedule**: Ensure the cron expression is correct
6. **Check environment**: Cron jobs run with minimal environment variables

#### Schedule Shows as "(macro)"

Some cron jobs use special macros like `@daily`, `@hourly`, `@reboot`, etc. These cannot be edited through the UI but can be:

* Toggled active/inactive
* Deleted
* Edited manually with `crontab -e`

### Best Practices

#### Testing

* Test commands manually before scheduling
* Start with a short interval (e.g., every minute) to verify the job works
* Check logs to confirm successful execution
* Update to the proper schedule once verified

#### Security

* Use minimal privileges when possible (user cron vs root cron)
* Avoid storing sensitive data in command strings
* Use dedicated scripts instead of inline commands
* Review and audit scheduled tasks regularly

#### Organization

* Use descriptive names for all jobs
* Add descriptions explaining purpose and dependencies
* Categorize jobs with appropriate types
* Document who created each job and why

#### Monitoring

* Redirect output to log files for debugging
* Set up notifications for critical jobs
* Regularly review job execution history
* Remove obsolete or unused jobs

#### Maintenance

* Keep crontab organized and documented
* Remove test jobs promptly
* Update descriptions when job purposes change
* Periodically review and clean up old entries

### Related Features

* **Terminal**: Execute commands and test scripts before scheduling
* **File Browser**: Upload and manage cron scripts
* **Server Metrics**: Monitor impact of scheduled tasks on server resources

### Keyboard Shortcuts

* **Enter**: Submit forms in modals
* **Escape**: Close modals (click outside or use close button)

***

**Need Help?** The Cron Job Manager provides contextual information throughout:

* Hover over badges and labels for explanations
* Check error messages for specific troubleshooting steps
* Use "View SSH command" to understand exact operations
* Review the schedule preview before saving changes


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://server-compass.gitbook.io/server-compass-docs/advance-guide/5.-your-first-cron-job.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
