Linux中使用crond工具创建定时任务

前言

  • crond是一个linux下的定时执行工具(相当于windows下的scheduled task),可以在无需人工干预的情况下定时地运行任务。crond工具提供crontab命令来设置定时任务,属于守护进程,只能精确到分钟,可以设定周期性执行Linux命令或者Shell脚本,每分钟crond都会检查是否有定时任务需要执行
  • 本次实验系统为CentOS 7

操作步骤

(1) 检查crond工具是否安装

yum list installed | grep crontabs

检查crond工具是否安装

  • 若未安装,则使用如下所示命令安装
sudo yum install crontabs

(2) 检查crond服务是否开启

  • 由于是CentOS7所以使用 systemctl 命令,而非 service 命令
systemctl status crond.service

检查crond服务是否开启

  • 若未开启,则使用如下所示命令开启服务
sudo systemctl start crond.service

(3) 使用crond工具创建任务计划

  • crontab命令使用方法
Usage:
 crontab [options] file
 crontab [options]
 crontab -n [hostname]

Options:
 -u <user>  define user
 -e         edit user's crontab
 -l         list user's crontab
 -r         delete user's crontab
 -i         prompt before deleting
 -n <host>  set host in cluster to run users' crontabs
 -c         get host in cluster to run users' crontabs
 -s         selinux context
 -x <mask>  enable debugging
 # 注意 crontab -r 是删除用户的所有定时任务(慎用!)
  • 可以通过 /etc/crontab 文件查看任务定义格式和设定任务执行环境
    任务定义格式

  • 以“每分钟定时将日期写入指定文件中”为例

方法1:使用crontab命令编辑当前用户定时任务(立即生效)**
crontab -e
  • 在编辑器中插入如下指令(注意此时不要追加用户,否则无法执行,因为此方法是直接设置当前用户的定时任务)
*/1 * * * * date >> /home/TomAndersen/currentDate
  • 检查插入结果
[tomandersen@hadoop101 bin]$ crontab -l
*/1 * * * * date >> /home/TomAndersen/currentDate
方法2:编辑 /etc/crontab 文件,按照格式插入(生效较慢)**
*/1 * * * * tomandersen date >> /home/TomAndersen/currentDate

(4) 检查是否设置成功

[tomandersen@hadoop101 bin]$ cat /home/TomAndersen/currentDate 
2020年 02月 09日 星期日 18:12:01 CST
2020年 02月 09日 星期日 18:13:01 CST
2020年 02月 09日 星期日 18:14:01 CST
2020年 02月 09日 星期日 18:15:01 CST
2020年 02月 09日 星期日 18:16:02 CST
2020年 02月 09日 星期日 18:17:01 CST
2020年 02月 09日 星期日 18:18:01 CST
2020年 02月 09日 星期日 18:19:01 CST
2020年 02月 09日 星期日 18:20:01 CST

End~

发布了15 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/TomAndersen/article/details/104237945