Linux Cron 定时任务


目标:

通过crontab命令在Linux系统设置定时任务

crontab命令

-u define user
-e edit user's crontab
-l list user's crontab
-r delete user's crontab
-i prompt before deleting
-n set host in cluster to run users' crontabs
-c get host in cluster to run users' crontabs
-s selinux context
-V print version and exit
-x enable debugging

准备定时任务的文件 /home/demo/cron-job

15 3 * * *  /bin/sh /home/demo/restart.sh

这种方式可能会手动执行restart.sh没问题,但是定时任务不生效,缺少环境变量导致。

在shell中执行时是能够找到环境变量的,但是在crontab中,它是不会自己导入环境变量的,需要我们指定。并将所有路径都写成绝对路径。

. /etc/profile 就是导入环境变量

15 3 * * * ./etc/profile; /bin/sh /home/demo/restart.sh
15 4 * * * ./etc/profile; /bin/sh /home/demo/restart.sh

通过文件给用户root设置定时任务

sudo crontab -u root /home/demo/cron-job

直接命令行修改用户root定时任务

sudo crontab -u root -e

查看用户roog的定时任务

sudo crontab  -u root -l

增加了crontab任务后,在/var/spool/cron目录下会有一个账号命名的文件。该文件的内容就是刚账号的crontab任务。

参考