本次目标是将指定python脚本每1s执行一次。
1 利用crontab定时运行任务l
输入命令
crontab -e
编辑:
每分钟执行一次:
* * * * * myCommand
每一小时执行一次
* */1 * * * command
更多示例(参考链接)
5 * * * * ls 指定每小时的第5分钟执行一次ls命令
30 5 * * * ls 指定每天的 5:30 执行ls命令
30 7 8 * * ls 指定每月8号的7:30分执行ls命令
30 5 8 6 * ls 指定每年的6月8日5:30执行ls命令
30 5 8 6 * ls 指定每年的6月8日5:30执行ls命令
30 6 * * 0 ls 指定每星期日的6:30执行ls命令
30 3 10,20 * * ls 每月10号及20号的3:30执行ls命令
25 8-11 * * * ls 每天8-11点的第25分钟执行ls命令
*/15 * * * * ls 每15分钟执行一次ls命令
30 6 */10 * * ls 每个月中,每隔10天6:30执行一次ls命令
22 4 * * * root run-parts /etc/cron.daily
#每天4:22以root身份执行/etc/cron.daily目录中的所有可执行文件,run-parts参数表示,执行后面目录中的所有可执行文件。
重定义输出
*/1 * * * * /root/XXXX.sh > /tmp/load.log 2>&1 &
crontab的命令构成为 时间+动作,其时间有分、时、日、月、周五种,操作符有
- * 取值范围内的所有数字
- / 每过多少个数字
- - 从X到Z
- ,散列数字
优点:简单方便,可以以日期周期为单位进行运行
缺点:不能按秒执行
参考链接: Linux Crontab 定时任务
2 以服务形式后台运行
利用systemctl命令设置快速启动,开机自启与自动重启。
首先在Python文件中利用sleep与无限循环设置每秒运行。
进入unit存放目录:
centos:
cd /usr/lib/systemd/system
ubuntu:
/etc/systemd/system
编辑.service配置文件
vim collector.service
[Unit]
Description=Runforver Process By send.py
After=zabbix-server.service
After=mariadb.service
After=network.target
[Service]
ExecStart=/usr/bin/python 脚本路径
ExecReload=/bin/kill -HUP $MAINPID
KillMode=control-group
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
参数详解:
[Unit]
Description:描述,
After:在network.target,auditd.service启动后才启动
ConditionPathExists: 执行条件
[Service]
EnvironmentFile:变量所在文件
ExecStart: 执行启动脚本
Restart: fail时重启
[Install]
Alias:服务别名
WangtedBy: 多用户模式下需要的
查看服务状态:
systemctl status collector
设置开机自启
systemctl enable collector
启动服务
systemctl start collector
查看服务状态
systemctl status collector
ps: 列出系统unit
systemctl list-unit-files
参考链接:
详解Linux 服务管理两种方式service和systemctl