centos定时任务crontab

 1、简介

crond 是linux下用来周期性的执行某种任务或等待处理某些事件的一个守护进程,与windows下的计划任务类似。任务调度分为两类:系统任务调度和用户任务调度。

系统任务是由 cron (crond) 这个系统服务来控制的,这个系统服务是默认启动的。

用户自己设置的计划任务则使用crontab 命令。

[root@localhost sugon]# crond --help
crond: invalid option -- '-'
Usage:
 crond [options]

Options:
 -h         print this message
 -i         deamon runs without inotify support
 -m <comm>  off, or specify prefered client for sending mails
 -n         run in foreground
 -p         permit any crontab
 -P         use PATH="/usr/bin:/bin"
 -c         enable clustering support
 -s         log into syslog instead of sending mails
 -x <flag>  print debug information

2、系统定时任务

系统任务调度:系统周期性所要执行的工作,比如写缓存数据到硬盘、日志清理等。在/etc/crontab文件,这个就是系统任务调度的配置文件。可添加定时任务,这里我使用命令:gedit  /etc/crontab来查看并添加定时任务,下面是文件内容。

注:系统定时任务是通过系统服务crond执行的,该服务默认开机启动。

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

3、用户的定时任务

用户定时任务的设定执行,我们需要使用到crontab服务,使用时要启动服务crond,crond服务通过crontab命令实现。

yum install crontabs  #安装crontab

由于crontab要用到crond服务,所以服务相关操作需要了解:

systemctl start crond  #启动服务
systemctl stop crond  #关闭服务
systemctl restart crond  #重启服务
systemctl reload crond  #重新载入配置
systemctl status crond  #查看服务状态
ntsysv  #查看开启启动项
systemctl enable crond  #加入开机启动项

1- 看下crontab命令介绍

[root@localhost sugon]# crontab --help
crontab: invalid option -- '-'
crontab: usage error: unrecognized option
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

2- 用户定时任务添加

命令:crontab -e

注:格式同/etc/crontab文档格式。每次编辑完某个用户的cron设置后,cron自动在/var/spool/cron下生成一个与此用户同名的文件,此用户的cron信息都记录在这个文件中,这个文件是不可以直接编辑的,只可以用crontab -e 来编辑。

例如添加脚本:*/5 * * * * root /home/crontab/check_sersync.sh > /dev/null 2>&1

脚本解释:以root用户每5分钟执行脚本/home/crontab/check_sersync.sh,并将错误信息记录到/dev/null下。

3- 用户定时任务查看

使用命令:crontab -l,就可看到刚添加的脚本了

4- 添加设置完成后,可重新载入配置,并重启下crond服务

systemctl reload crond  #重新载入配置
systemctl restart crond  #重启服务

4、权限文件

/etc/cron.deny:该文件中所列用户不允许使用crontab命令
/etc/cron.allow:该文件中所列用户允许使用crontab命令
/var/spool/cron/:所有用户crontab文件存放的目录,以用户名命名
/var/log/cron:日志文件,执行后记录可在此文件中查看

 

这篇就先写到这里,主要将centos定时任务总结,下一篇将解释,定时任务中参数含义与定义方法。

 

posted @ 2021-01-22 14:08  阳光宝贝-沐沐  阅读(380)  评论(0编辑  收藏  举报