1. 首页
  2. 技术知识

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

前言

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

操作步骤

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

yum list installed | grep crontabs

若未安装,则使用如下所示命令安装

sudo yum install crontabs

(2) 检查crond服务是否开启
由于是CentOS7所以使用 systemctl 命令,而非 service 命令

systemctl status crond.service

若未开启,则使用如下所示命令开启服务

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

2022年 02月 09日 星期日 18:12:01 CST

2022年 02月 09日 星期日 18:13:01 CST

2022年 02月 09日 星期日 18:14:01 CST

2022年 02月 09日 星期日 18:15:01 CST

2022年 02月 09日 星期日 18:16:02 CST

2022年 02月 09日 星期日 18:17:01 CST

2022年 02月 09日 星期日 18:18:01 CST

2022年 02月 09日 星期日 18:19:01 CST

2022年 02月 09日 星期日 18:20:01 CST
总结

以上所述是小编给大家介绍的Linux中使用crond工具创建定时任务,希望对大家有所帮助!

原创文章,作者:starterknow,如若转载,请注明出处:https://www.starterknow.com/106919.html

联系我们