crontab定时执行shell脚本

时间:2025-05-13 08:21:23

使用crontab你可以在指定的时间执行一个shell脚本或者一系列Linux命令。

例如系统管理员安排一个备份任务使其每天都运行。。我们一般是定时的执行shell脚本

一、步骤

(1)、编写好sh,设置成可执行,然后编辑crontab配置信息:

    到你的项目目录下,输入crontab –e,这样就以编辑模式打开个人的crontab配置文件,

(2)加入:

    0 0 * * * /home/linrui/

        每天凌晨运行指定的.sh文件

    或者:

    */1 * * * * sh xxxxxx/ /dev/null 2>&1 &

        每一分钟执行一次

(3)、然后退出保存,就会自动的根据你的配置执行脚本。

二、Cron 格式以及参数

以下是 crontab 文件的格式:

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

    o minute: 区间为 0  59

    o hour: 区间为 23

    o day-of-month: 区间为 31

    o month: 区间为 12. 1 1. 1212.

    o Day-of-week: 区间为 7. 周日可以是07.

参数配置:

    crontab e : 修改 crontab 文件如果文件不存在会自动创建。

    crontab l : 显示 crontab 文件。

    crontab -r : 删除 crontab 文件。

    crontab -ir : 删除 crontab 文件前提醒用户。 

三、Crontab 示例

1、在 凌晨00:01运行

    1 0 * * * /xxx/xxx/

2、每个工作日23:59都进行备份作业。

    59 11 * * 1,2,3,4,5 /xxx/xxx/  

或者如下写法:

    59 11 * * 1-5 /xxx/xxx/

3、每分钟运行一次命令

    */1 * * * * /xxx/linrui/

4、每个月的1 14:10 运行

    10 14 1 * * /xxx/xxx/