Purpose: Use crontab to perform scheduled tasks in the Linux environment, and output Hello World to the file!
1. Write a helloCron.sh script file
1.1 Create a directory: mkdir /app/test -p (-p: If the directory app is not created, it will be created directly)
1.2 Enter the directory: cd /app/test
1.3 Create a script for timing task execution: touch helloCron.sh
1.4 Edit helloCron.sh, as follows
#!/bin/bash
echo hello world! >> /app/test/helloCron.log # 创建一个.log文件用来作为脚本的输出文件
2. Modify script executable permissions
chmod +x helloCron.sh
3. Edit scheduled tasks
Use the command crontab -e to edit as follows
# 内容
# 每分钟执行一次,最少一分钟
*/1 * * * * /app/test/helloCron.sh
4. Reload the crontab service (Linux starts crontab by default)
/sbin/service crond reload
5. Common commands
crontab -l //查看定时任务列表
crontab -e //编辑定时任务
/sbin/service crond start //启动服务
/sbin/service crond stop //关闭服务
/sbin/service crond restart //重启服务
/sbin/service crond reload //重新载入配置
/sbin/service crond status //查看当前服务状态
ntsysv //进入交互界面,可以设置开机自启动
6. View scheduled tasks
7. View the output of the scheduled task execution script
Use tail -f helloCron.log to view
Additional information:
crontab 表达式分为5个部分,分别为:
minute hour day month week
分钟 小时 天 月 周 --口诀
其中:
minute: 表示分钟,可以是从0到59之间的任何整数。
hour:表示小时,可以是从0到23之间的任何整数。
day:表示日期,可以是从1到31之间的任何整数。
month:表示月份,可以是从1到12之间的任何整数。
week:表示星期几,可以是从0到7之间的任何整数,这里的0或7代表星期日。
command:要执行的命令,可以是系统命令,也可以是自己编写的脚本文件。
在以上各个字段中,还可以使用以下特殊字符:
星号(*):代表所有可能的值,例如month字段如果是星号,则表示在满足其它字段的制约条件后每月都执行该命令操作。
逗号(,):可以用逗号隔开的值指定一个列表范围,例如,“1,2,5,7,8,9”
中杠(-):可以用整数之间的中杠表示一个整数范围,例如“2-6”表示“2,3,4,5,6”
正斜线(/):可以用正斜线指定时间的间隔频率,例如“0-23/2”表示每两小时执行一次。同时正斜线可以和星号一起使用,例如*/10,如果用在minute字段,表示每十分钟执行一次。
ntsysv description:
Up and down keys: You can move between services in the middle box;
Space bar: It can be used to select the service you need, [*] means start;
Tab key: You can move between the box, OK, and Cancel;
[F1] key: It can display the description of the service.
Notice
If an error is reported: -bash: ntsysv: command not found
You can install yum: yum install ntsysv
For reference: https://www.jianshu.com/p/87df6dece7c1