liunx定时任务,centos定时任务

发布于:2025-05-20 ⋅ 阅读:(10) ⋅ 点赞:(0)

在这里插入图片描述

yum install cronie crontabs -y

直接运行
crond -n 在前台运行
crond -i 守护进程在没有inotify支持的情况下运行

systemctl service crond start    # 启动服务
systemctl enable crond.service   # 设置开机自启
sudo systemctl restart crond # 重启 cron 服务

systemctl service crond.service   # 检查服务是否正在运行

crontab -l    # 列出当前用户的定时任务(首次运行可能显示 "no crontab for root")
crontab -e    # 编辑定时任务
crontab -r    # 删除所有定时任务
* * * * * command_to_execute
五个星号分别代表:分钟(0-59)、小时(0-23)、日期(1-31)、月份(1-12)、星期(0-707 都代表周日)。

每天凌晨 2 点执行 backup.sh 脚本:
0 2 * * * /path/to/backup.sh

每小时的第 15 分钟执行 logrotate:
15 * * * * /usr/sbin/logrotate /etc/logrotate.conf

10秒执行一次,如果不需要严格的 10 秒间隔,也可以通过错开多个 cron 任务实现近似效果:
* * * * * /path/to/your_command
* * * * * (sleep 10; /path/to/your_command)
* * * * * (sleep 20; /path/to/your_command)
* * * * * (sleep 30; /path/to/your_command)
* * * * * (sleep 40; /path/to/your_command)
* * * * * (sleep 50; /path/to/your_command)

或者编写run_every_10s
#!/bin/bash
for i in {1..6}; do
    /path/to/your_command  # 替换为你的实际命令
    sleep 10
done
添加可执行权限
chmod +x /usr/local/bin/run_every_10s.sh
编写定时任务
crontab -e
编写
* * * * * /usr/local/bin/run_every_10s.sh


写日记

# 每分钟向 /tmp/cron_test.txt 写入当前时间
* * * * * date >> /tmp/cron_test.txt 2>&1

网站公告

今日签到

点亮在社区的每一天
去签到