宝塔用 systemd 设置定时执行 .sh 文件
前几天做了一个用宝塔自带计划(crontab) 来监控进程是否断了然后自动拉起,后来看到评论区其他小伙帮推荐 systemd 来执行,毕竟艺不压身,安排!
1.进入 /bin 目录创建脚本: vim swoole.sh
脚本内容:
#!/bin/bash
while true
do
procnum=` ps -ef|grep "SwooleWebSocketServer2.php"|grep -v grep|wc -l`
if [ $procnum -eq 0 ];
then
echo `date`'正在启动' >> /data/swoole.log #写入日志(这个注释需要删除不然会报错)
/www/server/php/74/bin/php /www/wwwroot/tp6swoole/app/controller/SwooleWebSocketServer2.php
fi
echo `date`'系统正在运行中' >> /data/swoole.log #写入日志
sleep 30 #等待30秒,不然系统会卡死
done
2.进入 /etc/systemd/system,创建服务 vim swoole.service (如果没写入权限执行:chmod +x swoole.sh )
//脚本内容:
[Unit]
Description=swoole service
[Service]
ExecStart=/bin/swoole.sh #你的.sh文件所在目录(这个注释需要删除不然会报错)
[Install]
WantedBy=multi-user.target
3.然后再同目录创建执行定时文件 vim swoole.timer (如果没写入权限执行:chmod +x swoole.timer )
//脚本内容:
[Unit]
Description=run swoole.sh every 10s
[Timer]
OnBootSec=10s #服务器启动后10秒自动执行(每次启动服务器后就不用再次输入命令启动脚本了)
OnUnitActiveSec=1m #一分钟执行一次(这个注释需要删除不然会报错)
Unit=swoole.service
[Install]
WantedBy=multi-user.target
4.创建好了后 启用定时任务
systemctl daemon-reload #重新加载配置
systemctl start swoole.timer # 启动定时任务
示例:其他定时执行
在系统启动15分钟后启动,并在系统运行时,每周启动一次。
[Unit] Description=Run foo weekly and on boot [Timer] OnBootSec=15min OnUnitActiveSec=1w [Install] WantedBy=timers.target
每周执行一次(周一凌晨0点)。激活后,如果错过了上次启动时间,,它会立即触发服务,例如由于系统断电:
[Unit] Description=Run foo weekly [Timer] OnCalendar=weekly Persistent=true [Install] WantedBy=timers.target
每天周一下午3点10分运行
如果需要具体的时间,我们可以给
OnCalendar
设定具体时间值,形如Year-Month-Day Hour:Minute:Second
[Unit] Description=Run timerecord on Monday 3:10 [Timer] OnCalendar=Mon *-*-* 15:10:00 Unit=timerecord [Install] WantedBy=timers.target
每隔5秒执行一次
[Unit] Description=Run timerecord every 5s [Timer] OnUnitActiveSec=5s # 可以设置为 5m,1h Unit=timerecord [Install] WantedBy=timers.target
每个小时的每隔10分钟 进行备份服务
[Unit] Description=backup [Timer] OnCalendar=*-*-* 0/1:0/10:00 Unit=backup [Install] WantedBy=multi-user.target
常用命令:
systemctl start swoole.timer# 启动定时任务
systemctl stop swoole.timer# 暂停定时任务
systemctl status swoole.timer# 查看定时任务服务状态
systemctl restart swoole.timer# 重启定时任务状态
systemctl list-timers --all # 查看定时任务列表
systemctl daemon-reload # 更改了配置文件后,需要重新加载
journalctl -u swoole.timer # 查看 swoole.timer 的日志
journalctl -u swoole # 查看 swoole.timer 和 swoole.service 的日志
journalctl -f # 从结尾开始查看最新日志
journalctl -f -u timer.timer # 从结尾开始查看 swoole.timer 的日志
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: