记一次centos7.2下用crontab执行定时任务的过程(初级)

实验目的:每分钟往某个文件写数据(crontab最小单位是分钟),具体shell命令我是放在一个文件里的。
先创建两个空文件:/tmp/a.txt(目标文件)和/tmp/a.sh(脚本文件)。

命令如下:

[root@localhost tmp]# touch a.txt a.sh

不能急着去编写cron表达式,先确定自己的脚本命令是否能够成功执行。

命令如下:

[root@localhost tmp]# /usr/bin/echo "test" >> /tmp/a.txt

可以用cat命令查看/tmp/a.txt文件是否多了一行,如果OK,那么我们再将此命令放入.sh文件。

如下:

[root@localhost tmp]# vi a.sh
#!/bin/bash
/usr/bin/echo "test" >> /tmp/a.txt

此时我们需要单独测试脚本文件执行结果

命令如下:

[root@localhost tmp]# /bin/bash /tmp/a.sh

如果OK,我们就可以编写crontab了。

[root@localhost tmp]# vi /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,
fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed
*/1  *  *  *  * root /bin/bash /tmp/a.sh

最下面这一行就是我自己写进去的。分三部分:1.cron表达式;2.执行用户;3.执行命令。

然后每分钟就会往/tmp/a.txt文件追加一行数据了。

最后给个小小的建议:命令要带上路径。比如:echo命令,要写成:/usr/bin/echo。

如果不知道echo命令的路径,可以用“which echo”命令查看。

转载于:https://www.cnblogs.com/subendong/p/8422157.html

你可能感兴趣的:(记一次centos7.2下用crontab执行定时任务的过程(初级))