Linux crontab 定时任务

tech2025-06-18  3

目录

1.定义2.命令解释3.查看 crontab 是否开启4.开启、关闭 crontab5.举个栗子

1.定义

crontab命令,是Linux中用于设置脚本周期性执行的命令。

/var/spool/cron/ 目录下存放的是每个用户包括root的crontab任务,每个任务以创建者的名字命名/etc/crontab 这个文件负责调度各种管理和维护任务。/etc/cron.d/ 这个目录用来存放任何要执行的crontab文件或脚本。我们还可以把脚本放在/etc/cron.hourly/etc/cron.daily/etc/cron.weekly/etc/cron.monthly 目录中,让它每小时/天/星期、月执行一次。

2.命令解释

# 查看当前用户的定时任务 $ crontab -l # 编辑当前用户的定时任务 $ crontab -e # 删除当前用户的定时任务 $ crontab -r # 查看指定用户的定时任务 $ crontab -u root -l

定时任务结构:

{minute} {hour} {day-of-month} {month} {day-of-week} {full-path-to-shell-script}

minute: 区间为 0 – 59hour: 区间为 0 – 23day-of-month: 区间为 0 – 31month: 区间为 1 – 12Day-of-week: 区间为 0 – 7(周日可以是0或7)

举个栗子:

*/1 * * * * 是指每分钟执行一次;

1 * * * * 是指每个小时1分钟的时候执行,比如9点1分、10点1分。。。

3.查看 crontab 是否开启

# 查看crontab服务状态 $ service crond status

开启状态,如图所示:

关闭状态,如图所示:

4.开启、关闭 crontab

# 开启 crontab 服务 $ service crond start # 关闭 crontab 服务 $ service crond stop

5.举个栗子

需求:创建一个文件,使用定时任务每秒写入一行当前日期。

1. 编写定期任务 hello.sh

(这里我个人创建到/home/backup路径下)

#!/bin/bash if [ -f ~/.bash_profile ]; then . ~/.bash_profile fi step=1 #间隔的秒数,不能大于60 for (( i = 0; i < 60; i = ( i + step ) )) do time=$(date "+%Y-%m-%d %H:%M:%S") echo $time >> /home/backup/hello.txt sleep $step done

2. 授权

$ chmod u+x hello.sh

3. 添加定时任务

# 编辑当前用户的定时任务 $ crontab -e

增加如下一行内容:

(每分钟,使用 /bin/sh,执行一次 /home/backup/hello.sh 文件)

*/1 * * * * /bin/sh /home/backup/hello.sh

4. 检验定时任务是否执行

$ tail -f /home/backup/hello.txt

完结撒花 ~ 个人总结,欢迎批评指正。

参考网址:

https://www.runoob.com/w3cnote/linux-crontab-tasks.html
最新回复(0)