crontab快速上手

crontab快速上手

crontab在类unix系统(Linux也能用)中用于设置周期性被执行的指令。crontab储存的指令被守护进程激活, crond常常在后台运行,每一分钟检查是否有预定的任务需要执行,此任务被称为cron jobs

1.crontab的作用

通过crontab我们可以定时执行指定的系统命令或者shell脚本,这个命令非常设合周期性的日志分析或数据备份等工作。

2.crontab的参数

Linux系统下打印的用法:

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

参数解释:

file       指定某个文件为crontab
-u <user>  指定用户
-e         编辑用户的crontab(默认当前)
-l         展示用户的crontab
-r         删除用户的crontab
-i         删除用户的crontab前提示
-n <host>  设置集群中的某台机去运行用户的crontab
-c         获得集群中的某台机去运行用户的crontab

3.编辑自己的crontab

编辑自己的crontab文件

$crontab -e 

编辑规则:

#minute   hour   day   month   week   command
#    *       *      *      *      *     命令 
#特殊符合
*          代表时间
,          代表不连接的时间
-          连续的时间
*/n        每隔n执行一次命令

示例:

*/1 * * * * /bin/echo "hello">>/root/hello.txt 
#每隔一分钟追加hello到文件/root/hello.txt中

1-2 6 * * * /bin/echo "hello">>/root/hello.txt
#06.01到06.02持续执行命令

4.用户crontab 文件位置

所有用户定义的crontab 文件都被保存在 /var/spool/cron目录中。其文件名与用户名一致。并且我们一般编辑的是用户任务调度。

用户任务调度:用户定期要执行的工作,比如用户数据备份。用户可以使用 crontab 工具来定制自己的计划任务。

5.系统的crontab文件位置

/etc/crontab 这个文件负责安排由系统管理员制定的维护系统以及其他任务的crontab。这个是系统周期性执行的任务,属于系统任务调度。

系统任务调度:系统周期性所要执行的工作,比如写缓存数据到硬盘、日志清理等。

扫描二维码关注公众号,回复: 11513396 查看本文章

如何编辑/etc/crontab文件,示例:

# 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


#其余更普通的crontab编辑一样,不过增加了指定用户
1-2 6 * * *  root   /bin/echo "hello">>/root/hello.txt

6.使用命令的权限设置

我们可以通过两个文件来设置那些用户能使用crontab命令。

/etc/cron.deny               #拒绝名单
/etc/cron.allow				 #允许名单

7.服务命令

service crond start //启动服务
service crond stop //关闭服务
service crond restart //重启服务
service crond reload //重新载入配置
service crond status  //查看状态

猜你喜欢

转载自blog.csdn.net/qq_43203949/article/details/106737386
今日推荐