# How to replace Cron by SystemD

Use `systemd` to schedule automated tasks

## 📌 Overview
On modern Linux systems, **systemd timers** can fully replace cron jobs.
Timers give you:

- Better logging (`journalctl`)
- Service dependencies (`After=`, `Requires=`)
- Reliable scheduling after boot
- Random delays to avoid load spikes
- Clear control (`start`, `stop`, `enable`, `status`)

This guide explains how to create a scheduled task using systemd.

---

# 1. Create a systemd Service
The service defines **what** will run — usually a script or command.

Example file:  
`/etc/systemd/system/myscript.service`

```ini
[Unit]
Description=Run my custom script

[Service]
Type=oneshot
ExecStart=/usr/local/bin/myscript.sh
```

Make your script executable:

```bash
chmod +x /usr/local/bin/myscript.sh
```

---

# 2. Create a systemd Timer
The timer defines **when** the service runs.

File:  
`/etc/systemd/system/myscript.timer`

```ini
[Unit]
Description=Run my script every day at 03:00

[Timer]
OnCalendar=03:00
Persistent=true

[Install]
WantedBy=timers.target
```

`Persistent=true` ensures missed runs (e.g., machine off) are executed at the next boot.

---

# 3. Enable and Start the Timer

Reload systemd and activate the timer:

```bash
systemctl daemon-reload
systemctl enable --now myscript.timer
```

---

# 4. Verify the Timer is Working

List active timers:

```bash
systemctl list-timers
```

View logs for the executed service:

```bash
journalctl -u myscript.service
```

---

# 5. Useful Scheduling Examples

## Run Daily at 3 AM
```ini
OnCalendar=03:00
```

## Run Every 15 Minutes
```ini
OnCalendar=*:0/15
```

## Run Every Monday at 09:00
```ini
OnCalendar=Mon 09:00
```

## Run on Reboot (after 5 minutes)
```ini
OnBootSec=5min
```

## Run Hourly
```ini
OnCalendar=hourly
```

## Run Monthly
```ini
OnCalendar=monthly
```

---

# 6. Example: Run a Script Every 30 Minutes

### `/etc/systemd/system/healthcheck.service`

```ini
[Unit]
Description=Health check script

[Service]
Type=oneshot
ExecStart=/usr/local/bin/healthcheck.sh
```

### `/etc/systemd/system/healthcheck.timer`

```ini
[Unit]
Description=Run health check every 30 minutes

[Timer]
OnCalendar=*:0/30

[Install]
WantedBy=timers.target
```

Enable:

```bash
systemctl enable --now healthcheck.timer
```

---

# 7. Troubleshooting

### Check Timer Status
```bash
systemctl status myscript.timer
```

### Check Service Logs
```bash
journalctl -u myscript.service
```

### Manually Trigger the Task
```bash
systemctl start myscript.service
```

---

# ✔ Summary
systemd timers are a robust and modern alternative to classic cron:

- More control
- Better logging
- Cleaner dependency management
- Easier to maintain