大多数现代Linux发行版(如Ubuntu 16.04+, CentOS 7+, Debian 8+)已默认安装Systemd。如果需要手动安装:
# 对于基于Debian的系统
sudo apt-get update
sudo apt-get install systemd
# 对于基于RHEL的系统
sudo yum install systemd
# 启动服务
sudo systemctl start service_name
# 停止服务
sudo systemctl stop service_name
# 重启服务
sudo systemctl restart service_name
# 查看服务状态
sudo systemctl status service_name
# 启用开机自启
sudo systemctl enable service_name
# 禁用开机自启
sudo systemctl disable service_name
# 查看所有已启用的服务
sudo systemctl list-unit-files --state=enabled
/etc/systemd/system/
目录下):sudo nano /etc/systemd/system/my_service.service
[Unit]
Description=My Custom Service
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/python3 /path/to/your/script.py
Restart=on-failure
User=your_username
Group=your_groupname
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl start my_service
sudo systemctl enable my_service
大多数Linux发行版已预装Cron。如果需要手动安装:
# 对于基于Debian的系统
sudo apt-get update
sudo apt-get install cron
# 对于基于RHEL的系统
sudo yum install cronie
# 启动服务
sudo systemctl start cron # 或 crond (取决于发行版)
# 启用开机自启
sudo systemctl enable cron
crontab -e
# 每分钟执行一次命令
* * * * * /path/to/command
# 每天凌晨2点执行
0 2 * * * /path/to/command
# 每周一上午8点执行
0 8 * * 1 /path/to/command
# 每月1号中午12点执行
0 12 1 * * /path/to/command
# 每5分钟执行一次
*/5 * * * * /path/to/command
crontab -l
crontab -r
系统级crontab位于/etc/crontab
,编辑方式:
sudo nano /etc/crontab
格式与用户crontab类似,但需要指定用户:
* * * * * username /path/to/command
Systemd提供了定时器功能,可以作为Cron的替代方案:
/etc/systemd/system/my_timer.service
):[Unit]
Description=My Timer Job
[Service]
Type=oneshot
ExecStart=/path/to/your/script.sh
/etc/systemd/system/my_timer.timer
):[Unit]
Description=Runs my_timer.service every day at midnight
[Timer]
OnCalendar=*-*-* 00:00:00
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable my_timer.timer
sudo systemctl start my_timer.timer
systemctl list-timers --all
日志记录:
journalctl -u service_name
错误处理:
安全性:
选择方案:
调试技巧: