linux的定时任务crond(crontab)服务

1. crond是什么?

Crond是linux系统中用来定期执行命令或者指定程序任务的一种服务或者软件。

一般安装完C5/C6系统的时候,crond就会默认存在了。

我们优化开启自启动服务的时候,第一个就是crond

Crond服务默认情况(每分钟),会检查系统中是否由需要执行的定时任务,如果有,就会根据事先定义好的规则执行这个任务。

 

秒级任务:

1)crond自身无能为力

2)自己写守护进程设shell循环

3)Quartz也可实现秒级任务

 

linux定时任务分类:

1、系统自身的定期执行的任务

 

2、用户执行的定时任务

[root@dancheng_linux log]# crontab -l

#time sync by dancheng at 2017-11-12

*/5**** /usr/sbin/ntpdate time.nist.gov > /dev/null 2>&1

 

提示:crond是一个定时任务守护进程,而crontab是用户用来设置定时任务规则的命令

几乎每个服务器都会用到crond服务

crontab                    功能:定时任务

                          -l查询定时任务       -e编辑定时任务

 

 

[root@dancheng_linux ~]# cat /etc/crontab

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

[分 时 日 月 周]

[root@dancheng_linux ~]#

 

 

00 17-19 * * * /bin/sh/script/dancheng.sh     每天17、18和19点整点分别执行dancheng.sh

30 17,18,19 * * * /bin/sh/script/dancheng.sh 每天17、18和19点的半点时刻执行dancheng.sh

*/10 * * * * cmd             每10秒执行一次任务

 

启动/停止crond服务

/sbin/service crond start

/sbin/service crond stop

/sbin/service crond restart

 

查看定时任务:

[root@dancheng_linux log]# crontab -l

#time sync by dancheng at 2017-11-12

*/5 * * * * /usr/sbin/ntpdate time.nist.gov > /dev/null 2>&1

* * * * *  echo "dancheng" >> /home/dancheng/log/dancheng.log  > /dev/null 2>&1

 

编辑定时任务:

crontab -e

#time sync by dancheng at 2017-11-12

*/5 * * * * /usr/sbin/ntpdate time.nist.gov > /dev/null 2>&1

* * * * *  echo "dancheng" >> /home/dancheng/log/dancheng.log  > /dev/null 2>&1

~

~

~

"/tmp/crontab.FLRDXL" 3L, 178C

 

 

 

 

书写crontab定时任务的多个基本要领:

例1:每分钟答应自己名字全拼到 “/server/log/自己名字文件”中

* * * * *  echo "dancheng" >> /home/dancheng/log/dancheng.log  

 

例2:每周六、日上午9:00和下午14:00发送消息到/home/dancheng/kkk/log/test.sh,这个脚本的功能是打印当天的日期格式为2017-12-13,随时追加到一个文件里或者干脆屏幕输出。

1)创建目录和编写脚本

[root@dancheng_linux log]# echo 'date +%F' > test.sh

[root@dancheng_linux log]# sh test.sh

2017-12-13

 

2)书写定时任务

[root@dancheng_linux log]# echo "#study to school" >> /var/spool/cron/root

[root@dancheng_linux log]# echo "00 09,14 * * 6,7 /bin/sh /home/dancheng/kkk/log/test.sh" >> /var/spool/cron/root

[root@dancheng_linux log]# crontab -l|tail -2

#study to school

00 09,14 * * 6,7 /bin/sh /home/dancheng/kkk/log/test.sh

 

3)给出标准规范的答案

#study to school

00 09,14 * * 6,7 /bin/sh /home/dancheng/kkk/log/test.sh > /dev/null 2>&1

猜你喜欢

转载自blog.csdn.net/dancheng1/article/details/78849103