Linux Job Scheduling Without Cron

Published August 13, 2024

This article covers three alternative methods for scheduling tasks in Linux without using cron: sleep loops, systemd timers, and Anacron. You'll learn how to set up each method, understand their benefits and limits, and see practical examples of their use. The article will help you pick the right scheduling approach for your needs, whether you're working with simple scripts or complex system tasks.

Key Takeaways

  • Sleep loops offer a simple, flexible method for task scheduling on any Linux system without additional software.

  • Systemd timers provide precise scheduling with system event triggers and integrated logging for modern Linux systems.

  • Anacron is ideal for systems with irregular uptime, ensuring tasks run even if the scheduled time is missed.

  • Choose the scheduling method based on system uptime, timing precision needs, ease of setup, system compatibility, and task complexity.

  • Each method has unique advantages: sleep loops for simplicity, systemd timers for accuracy, and Anacron for reliability on intermittently used systems.

Sleep Loop Method

How Sleep Loops Work

Sleep loops are a way to schedule tasks in Linux without cron. This method uses shell commands to create a loop that runs a task at set times.

Here's a diagram showing the sleep loop process:

graph TD A[Start] --> B[while true] B --> C[do] C --> D[Execute Command/Script] D --> E[sleep for specified time] E --> C B --> F[& Run in background]

Basic Sleep Loop Example

while true; do
    echo "Task executed at $(date)"
    sleep 60
done &

This loop prints a message with the current date every 60 seconds.

Tip: Use the 'date' Command for Precise Timing

To run tasks at specific times, use the 'date' command to calculate sleep durations:

while true; do
    current_time=$(date +%s)
    target_time=$(date -d "23:00" +%s)
    sleep_duration=$((target_time - current_time))

    if [ $sleep_duration -lt 0 ]; then
        sleep_duration=$((sleep_duration + 86400))
    fi

    sleep $sleep_duration

    # Run your task here
    echo "Task executed at $(date)"
done &

This script runs the task daily at 23:00, adjusting the sleep duration based on the current time.

Complex Task Example

while true; do
    /path/to/your/script.sh
    sleep 3600
done &

This example runs a script every hour (3600 seconds).

Advantages and Limitations

Advantages Limitations
Simple to set up and understand Less precise timing than cron or systemd timers
No need for extra software No built-in error handling or logging
Works on any Linux system with a shell Runs until manually stopped
Easy to change on the fly May not handle system restarts well

Best Use Cases

Sleep loops are best for:

  • Quick, temporary scheduling needs
  • Testing and development environments
  • Systems where cron or systemd are not available
  • Tasks that need to run non-stop with a fixed interval

Systemd Timers

Setting Up Systemd Timers

Systemd timers schedule tasks in Linux systems that use systemd as their init system. To set up a systemd timer, create two files: a timer unit and a service unit.

Here's a guide with examples:

  1. Create a timer unit file:
sudo nano /etc/systemd/system/backup.timer

Add the following content:

[Unit]
Description=Daily Backup Timer

[Timer]
OnCalendar=*-*-* 02:00:00
Unit=backup.service

[Install]
WantedBy=timers.target
  1. Create a service unit file:
sudo nano /etc/systemd/system/backup.service

Add the following content:

[Unit]
Description=Daily Backup Service

[Service]
ExecStart=/home/user/scripts/daily_backup.sh

[Install]
WantedBy=multi-user.target
  1. Enable and start the timer:
sudo systemctl enable backup.timer
sudo systemctl start backup.timer

This example sets up a daily backup task that runs at 2 AM every day.

Tip: Reload Systemd After Changes

After creating or modifying systemd unit files, reload the systemd manager configuration:

sudo systemctl daemon-reload

This ensures that systemd recognizes the new or updated unit files.

Customizing Systemd Timer Schedules

Systemd timers use the OnCalendar option to set schedules. Here are examples of schedules:

Task OnCalendar Setting Description
Daily Log Rotation *-*-* 23:59:00 Rotate logs daily at 11:59 PM
Weekly System Update Mon *-*-* 05:00:00 Update system every Monday at 5 AM
Hourly Database Backup *:00 Backup database every hour
Monthly Report Generation 1 *-*-* 09:00:00 Generate reports on the 1st of every month at 9 AM

You can also use other time expressions:

OnBootSec

Runs the task a set time after boot. For example:

[Timer]
OnBootSec=5min

This runs a task 5 minutes after the system boots, useful for initialization scripts.

OnUnitActiveSec

Runs the task at set intervals after the service was last activated. For example:

[Timer]
OnUnitActiveSec=30min

This is useful for tasks that need to run often, like checking for software updates every 30 minutes.

Visualizing Systemd Timer Flow

graph TD A[Create Timer Unit] --> B[Create Service Unit] B --> C[Enable Timer] C --> D[Start Timer] D --> E[Timer Triggers] E --> F[Service Executes] F --> G[Task Completes] G --> E

Practical Use Cases

  • Log Cleanup: Set up a timer to remove old log files weekly.
  • Database Backups: Create hourly database backups during business hours.
  • System Updates: Schedule automatic system updates during off-hours.
  • Temporary File Cleanup: Clear temporary files daily to free up disk space.

Example: Temporary File Cleanup Timer

Create a timer for daily cleanup of temporary files:

  1. Create the timer file (/etc/systemd/system/cleanup.timer):
    
    [Unit]
    Description=Daily Temporary File Cleanup

[Timer] OnCalendar=--* 03:00:00 Unit=cleanup.service

[Install] WantedBy=timers.target


2. Create the service file (/etc/systemd/system/cleanup.service):
```ini
[Unit]
Description=Temporary File Cleanup Service

[Service]
ExecStart=/bin/sh -c 'find /tmp -type f -atime +7 -delete'

[Install]
WantedBy=multi-user.target

This setup deletes files in /tmp that haven't been accessed in 7 days, running daily at 3 AM.

Monitoring Systemd Timers

To check the status of your timers:

systemctl list-timers

This command shows all active timers, their last and next trigger times, and the associated unit.

Advantages of Systemd Timers

  • Integration with systemd logging
  • Accurate timing even if a scheduled time is missed (e.g., system was off)
  • Can trigger based on system events, not just time
  • Easy to manage with standard systemd commands

For more information on systemd timers, refer to the official systemd documentation.

Anacron for Irregular Schedules

Understanding Anacron's Functionality

Anacron is a job scheduling program for systems with irregular uptime. It runs tasks even if the system is offline during the scheduled time. This is useful for:

  • Personal computers used intermittently
  • Servers that may be powered down occasionally
  • Devices in environments with unreliable power supply

Tip: Verify Anacron Installation

To check if Anacron is installed on your system, use the command:

which anacron

If installed, it will return the path to the Anacron executable.

How Anacron Works

graph TD A[System Startup] --> B[Anacron Checks Last Run Time] B --> C{Tasks Missed?} C -->|Yes| D[Run Missed Tasks] C -->|No| E[Wait for Next Scheduled Run] D --> E E --> F[Run Tasks at Scheduled Time]

Advanced Anacron Usage

Using Environment Variables

Anacron lets you set environment variables for your jobs. This can help configure paths, set options, or pass information to scripts.

Example:

SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=admin@example.com

1 5 daily-backup HOME=/home/user /path/to/backup-script.sh

In this example, the HOME variable is set for the daily-backup job.

Handling Job Output

By default, Anacron sends job output via email to the local user. You can redirect output to a file or discard it:

  • Redirect to a file: 1 5 daily-task /path/to/script.sh > /path/to/logfile 2>&1
  • Discard output: 1 5 daily-task /path/to/script.sh > /dev/null 2>&1

Using Anacron with Cron

For systems that are usually on but may be off occasionally, you can combine Anacron with cron for more flexibility:

  1. Create an Anacron job file (e.g., /etc/cron.daily/anacron-daily):
#!/bin/bash
/usr/sbin/anacron -s
  1. Make it executable:
sudo chmod +x /etc/cron.daily/anacron-daily

This setup runs Anacron daily through cron, allowing it to catch up on missed jobs when the system is on.

Comparing Scheduling Methods

Pros and Cons

Sleep Loops

Pros Cons
- Simple to set up - Limited features
- Works on any Linux system - Less precise timing
- No extra software needed - No built-in error handling or logging
- Easy to modify - Runs until stopped
- May not handle system restarts well

Tip: Enhancing Sleep Loops

To improve sleep loops, add basic error handling and logging. Use try-except blocks to catch errors and write them to a log file. This helps track issues without losing the simplicity of sleep loops.

Systemd Timers

Pros Cons
- Modern approach with systemd - Only for systems using systemd
- Accurate timing - Requires more setup than sleep loops
- Can trigger based on system events - May be complex for simple needs
- Managed with systemd commands
- Integrates with systemd logging

Anacron

Pros Cons
- Good for systems with irregular uptime - Less precise timing than other methods
- Runs missed jobs when system is available - Not for tasks needing exact timing
- Simple configuration - Limited to daily, weekly, or monthly schedules
- Built-in delay to avoid overload at startup

Choosing the Right Method

To select the best scheduling method, consider these factors:

graph TD A[Factors to Consider] B[System Uptime] C[Timing Precision] D[Ease of Setup] E[System Compatibility] F[Task Complexity] A --> B A --> C A --> D A --> E A --> F
  1. System uptime: For always-on systems, systemd timers or sleep loops work well. For intermittent use, Anacron is better.

  2. Timing precision: For exact timing, use systemd timers. Sleep loops and Anacron are less precise.

  3. Ease of setup: Sleep loops are simplest, while systemd timers and Anacron need more configuration.

  4. System compatibility: Sleep loops work on any Linux system. Systemd timers need systemd, and Anacron may need separate installation.

  5. Task complexity: For simple tasks, sleep loops might be enough. For complex scheduling, use systemd timers or Anacron.

By considering these factors, you can choose the method that fits your needs and system.

Additional Resources