Pertemuan 12: Penjadwalan Tugas Otomatis

1. Pendahuluan

Penjadwalan tugas otomatis adalah kemampuan sistem untuk menjalankan tugas-tugas secara otomatis pada waktu yang telah ditentukan.

Critical Aspect: Ini merupakan aspek kritis dalam administrasi sistem untuk melakukan tugas-tugas rutin seperti backup, pembersihan, monitoring, dan pelaporan tanpa intervensi manual.
Otomasi
Reduce manual intervention
Konsistensi
Ensure regular execution
Efisiensi
Utilize off-peak hours
Reliabilitas
Run without admin presence

2. Konsep Dasar Penjadwalan Tugas

Mengapa Penjadwalan Tugas Penting?
Otomasi

Mengurangi intervensi manual dan human error

  • Automated repetitive tasks
  • Reduce manual errors
  • Standardize processes
  • Improve efficiency
Konsistensi

Menjamin tugas dilakukan secara teratur dan konsisten

  • Regular maintenance
  • Consistent execution
  • Predictable outcomes
  • Reliable operations
Efisiensi

Memanfaatkan waktu ketika sistem tidak sibuk (off-peak)

  • Off-hours execution
  • Resource optimization
  • Cost reduction
  • Performance optimization
Reliabilitas

Tugas berjalan bahkan ketika administrator tidak tersedia

  • 24/7 operations
  • Holiday coverage
  • Disaster recovery
  • Business continuity
Jenis Tugas yang Dijadwalkan
Kategori Tugas Contoh Frekuensi Kompleksitas
System Maintenance Backup, update, pembersihan file temporary Daily/Weekly Medium
Monitoring & Reporting Generate report, system health checks Hourly/Daily Low-Medium
Data Processing ETL processes, data synchronization Daily/Weekly High
Application Tasks Batch jobs, database maintenance, cache clearing Hourly/Daily Medium-High
Security Tasks Virus scanning, log rotation, security updates Daily/Weekly Medium

3. Cron: Time-based Job Scheduler di Linux

Konsep Dasar Cron
Daemon

Service crond yang berjalan di background

# Check cron status
systemctl status cron

# Restart cron service
sudo systemctl restart cron
Crontab

File konfigurasi yang berisi jadwal tugas

# Edit user crontab
crontab -e

# View current crontab
crontab -l

# Remove crontab
crontab -r
Format Waktu

minute hour day month day-of-week command

# Basic format
* * * * * command

# Example
0 2 * * * /backup.sh
Format Crontab
Minute 0-59
Hour 0-23
Day of Month 1-31
Month 1-12
Day of Week 0-6 (0=Sunday)
Command Command to execute
Special Characters
*

Any value

Matches all values
,

Value list separator

e.g., 1,3,5
-

Range of values

e.g., 1-5
/

Step values

e.g., */2 for every 2 units
Contoh Crontab
Basic Examples
# Setiap menit
* * * * * /path/to/command

# Setiap hari jam 2:30 AM
30 2 * * * /path/to/command

# Setiap Senin jam 4:00 PM
0 16 * * 1 /path/to/command

# Setiap 1 Januari jam 00:01
1 0 1 1 * /path/to/command

# Setiap 10 menit
*/10 * * * * /path/to/command
Advanced Examples
# Setiap hari kerja (Senin-Jumat) jam 6:00 PM
0 18 * * 1-5 /path/to/command

# Setiap 2 jam selama jam kerja (9 AM - 5 PM)
0 9-17/2 * * * /path/to/command

# Setiap hari Sabtu dan Minggu jam 3 AM
0 3 * * 6,7 /path/to/command

# Setiap 5 menit pada hari kerja
*/5 * * * 1-5 /path/to/command

# Setiap bulan pertama jam 2 AM
0 2 1 * * /path/to/command

4. Systemd Timers: Modern Alternative untuk Cron

Konsep Systemd Timers
Timer Units

File .timer yang mendefinisikan jadwal

# Example: /etc/systemd/system/backup.timer
[Unit]
Description=Run database backup daily
Requires=backup.service

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target
Service Units

File .service yang berisi tugas yang dijalankan

# Example: /etc/systemd/system/backup.service
[Unit]
Description=Database Backup Service

[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
User=backup-user

[Install]
WantedBy=multi-user.target
Advantages of Systemd Timers
Integration

Integrasi dengan systemd

Better system integration
Dependency Management

Dependency management

Service dependencies
Flexibility

Lebih fleksibel

More scheduling options
Manage Systemd Timers
Basic Management
# Enable dan start timer
sudo systemctl enable backup.timer
sudo systemctl start backup.timer

# Check status
sudo systemctl status backup.timer

# List all timers
sudo systemctl list-timers

# Manual trigger service
sudo systemctl start backup.service
Advanced Management
# Check timer details
systemctl show backup.timer

# View timer calendar
systemctl calendar backup.timer

# Reload systemd
sudo systemctl daemon-reload

# Disable timer
sudo systemctl disable backup.timer
sudo systemctl stop backup.timer

# View logs
journalctl -u backup.service

5. Windows Task Scheduler

Graphical Interface
Task Scheduler GUI

Graphical task scheduling interface

  • Task Scheduler (taskschd.msc)
  • Create Basic Task atau Create Task
  • Triggers (waktu, event, startup, logon)
  • Actions (start program, send email, show message)
# Launch Task Scheduler
taskschd.msc

# atau melalui Run dialog
Win + R → taskschd.msc
PowerShell Management
# Create new scheduled task
$Action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "C:\Scripts\backup.ps1"
$Trigger = New-ScheduledTaskTrigger -Daily -At "2:00 AM"
Register-ScheduledTask -Action $Action -Trigger $Trigger -TaskName "DailyBackup" -Description "Daily database backup"

# Manage existing tasks
Get-ScheduledTask -TaskName "DailyBackup"
Start-ScheduledTask -TaskName "DailyBackup"
Disable-ScheduledTask -TaskName "DailyBackup"
Unregister-ScheduledTask -TaskName "DailyBackup" -Confirm:$false
Command Line (schtasks)
Basic schtasks Commands
# Create task
schtasks /create /tn "DailyBackup" /tr "C:\Scripts\backup.bat" /sc daily /st 02:00

# Run task immediately
schtasks /run /tn "DailyBackup"

# Delete task
schtasks /delete /tn "DailyBackup" /f

# Query task information
schtasks /query /tn "DailyBackup" /fo list

# Change task schedule
schtasks /change /tn "DailyBackup" /st 03:00
Advanced schtasks Examples
# Create task with specific user
schtasks /create /tn "BackupWithCreds" /tr "C:\backup.bat" /sc daily /st 02:00 /ru "DOMAIN\User" /rp "password"

# Create task that runs weekly
schtasks /create /tn "WeeklyReport" /tr "C:\report.bat" /sc weekly /d MON /st 06:00

# Create task that runs on system startup
schtasks /create /tn "StartupTask" /tr "C:\startup.bat" /sc onstart

# Create task that runs when user logs on
schtasks /create /tn "LogonTask" /tr "C:\logon.bat" /sc onlogon

6. Advanced Scheduling Techniques

Anacron: Untuk Sistem yang Tidak Selalu Menyala
Anacron Concept

Cocok untuk desktop atau laptop yang tidak 24/7

  • Menjalankan tugas yang terlewat ketika sistem dinyalakan
  • Ideal untuk workstations
  • Simple configuration
  • Backward compatible dengan cron
Konfigurasi Anacron
# /etc/anacrontab
# period in days delay in minutes job-identifier command

1 5 cron.daily /usr/local/bin/daily-job.sh
7 10 cron.weekly /usr/local/bin/weekly-job.sh
30 15 cron.monthly /usr/local/bin/monthly-job.sh

# Format:
# [period] [delay] [job-identifier] [command]
Lock Files: Mencegah Overlapping Execution
Script dengan Lock File
#!/bin/bash
# Script dengan lock file

LOCKFILE="/var/run/myscript.lock"

# Check if lock file exists
if [ -f "$LOCKFILE" ]; then
  echo "Script is already running!"
  exit 1
fi

# Create lock file
touch "$LOCKFILE"

# Trap untuk memastikan lock file dihapus saat script exit
trap 'rm -f "$LOCKFILE"; exit' INT TERM EXIT

# Main script logic
echo "Starting main task..."
/path/to/actual/script.sh

# Cleanup
rm -f "$LOCKFILE"
trap - INT TERM EXIT

echo "Script completed successfully"

7. Error Handling dan Notification

Basic Error Handling
Script dengan Error Handling
#!/bin/bash
# Script dengan error handling dan email notification

LOG_FILE="/var/log/myscript.log"
RECIPIENT="admin@company.com"

{
  echo "Starting script at $(date)"

  # Main commands dengan error checking
  /usr/local/bin/task1.sh || exit 1
  /usr/local/bin/task2.sh || exit 1
  /usr/local/bin/task3.sh || exit 1

  echo "Script completed successfully at $(date)"
} >> "$LOG_FILE" 2>&1

# Check exit status
if [ $? -ne 0 ]; then
  echo "Script failed at $(date)" | mail -s "Script Failure" "$RECIPIENT"
  exit 1
fi
Advanced Notification System
#!/bin/bash
# advanced_error_handler.sh

SCRIPT_NAME=$(basename "$0")
LOG_FILE="/var/log/${SCRIPT_NAME}.log"
MAX_RETRIES=3
RETRY_DELAY=60

send_alert() {
  local subject="$1"
  local message="$2"
  echo "$(date): $message" >> "$LOG_FILE"
  echo "$message" | mail -s "$subject" "admin@company.com"
  # Optional: Send to Slack/Teams
  # curl -X POST -H 'Content-type: application/json' --data "{\"text\":\"$message\"}" $WEBHOOK_URL
}

retry_command() {
  local cmd="$1"
  local retries=0
  
  while [ $retries -lt $MAX_RETRIES ]; do
    if $cmd; then
      return 0
    fi
    ((retries++))
    sleep $RETRY_DELAY
  done
  return 1
}
Email Notification Examples
Success Notification
#!/bin/bash
# success_notification.sh

JOB_NAME="Daily Backup"
DURATION="$1"
RECIPIENT="admin@company.com"

cat << EOF | mail -s "Success: $JOB_NAME Completed" "$RECIPIENT"
Job: $JOB_NAME
Status: SUCCESS
Completion Time: $(date)
Duration: $DURATION

Details:
- All tasks completed successfully
- No errors encountered
- Output logs attached

System: $(hostname)
EOF
Failure Notification
#!/bin/bash
# failure_notification.sh

JOB_NAME="Daily Backup"
ERROR_MSG="$1"
RECIPIENT="admin@company.com"

cat << EOF | mail -s "FAILURE: $JOB_NAME Failed" "$RECIPIENT"
URGENT: Job Failure Alert

Job: $JOB_NAME
Status: FAILED
Failure Time: $(date)
Error: $ERROR_MSG

Required Actions:
1. Investigate the failure cause
2. Check system logs
3. Restart the job if necessary
4. Update documentation if needed

System: $(hostname)
EOF

8. Monitoring dan Logging Scheduled Tasks

Cron Logging
Enable Cron Logging
# Enable cron logging (biasanya di /etc/rsyslog.conf)
sudo vi /etc/rsyslog.conf

# Uncomment atau add line:
cron.* /var/log/cron.log

# Restart rsyslog
sudo systemctl restart rsyslog

# Lihat cron logs
sudo grep CRON /var/log/syslog
sudo tail -f /var/log/cron.log # Pada beberapa distribusi

# Check specific user cron logs
sudo grep "CRON.*username" /var/log/syslog
Custom Logging untuk Scheduled Tasks
# Dalam crontab - redirect output
* * * * * /path/to/script.sh >> /var/log/script.log 2>&1

# Dengan timestamp
* * * * * /path/to/script.sh 2>&1 | while read line; do echo "[$(date)] $line"; done >> /var/log/script.log

# Advanced logging dengan rotation
* * * * * /path/to/script.sh 2>&1 | logger -t myscript

# Log ke systemd journal
* * * * * /path/to/script.sh 2>&1 | systemd-cat -t myscript

# Custom log format
* * * * * /path/to/script.sh 2>&1 | awk '{print strftime("[%Y-%m-%d %H:%M:%S]"), $0}' >> /var/log/script.log
Monitoring Execution
Script untuk Memeriksa Eksekusi Tugas
#!/bin/bash
# check_task_execution.sh

TASK_NAME="daily-backup"
LAST_RUN_FILE="/var/last-run-$TASK_NAME"
MAX_HOURS=24
ALERT_EMAIL="admin@company.com"

# Check jika tugas sudah berjalan hari ini
if [ -f "$LAST_RUN_FILE" ]; then
  LAST_RUN=$(cat "$LAST_RUN_FILE")
  NOW=$(date +%s)
  HOURS_SINCE_RUN=$((($NOW - $LAST_RUN) / 3600))
  
  if [ $HOURS_SINCE_RUN -gt $MAX_HOURS ]; then
    echo "ALERT: Task '$TASK_NAME' hasn't run in $HOURS_SINCE_RUN hours" | mail -s "Task Monitoring Alert" "$ALERT_EMAIL"
  else
    echo "Task '$TASK_NAME' last ran $HOURS_SINCE_RUN hours ago - OK"
  fi
else
  echo "ALERT: Task '$TASK_NAME' has never run" | mail -s "Task Monitoring Alert" "$ALERT_EMAIL"
fi

# Update last run date (call this from your task script)
update_last_run() {
  date +%s > "$LAST_RUN_FILE"
}

12. Interactive Cron Job Generator

Cron Expression Generator
Schedule Configuration:
Generated Cron Job:
# Your cron job will appear here
Explanation:
Select options to see explanation...
Next Run Times:
Next executions will be calculated...

Ringkasan Pembelajaran

Pada pertemuan ini kita telah mempelajari penjadwalan tugas otomatis yang komprehensif, termasuk cron, systemd timers, dan Windows Task Scheduler.

Key Takeaways:
  • Pemahaman cron syntax dan special characters
  • Systemd timers sebagai modern alternative
  • Windows Task Scheduler management
  • Error handling dan monitoring techniques
Next Topic Preview:

Pertemuan berikutnya: Optimasi Sistem - performance tuning dan system optimization techniques.