Linux系统定时任务

1、什么是定时任务?

周期性的执行任务计划的软件,Linux定时任务的常用软件crond。

2、作用:使用定时任务软件,可以每天,每小时按你需求重复的执行一项工作。

例如:备份 都是0点以后,2点爬起来备份,4点以后睡觉。

需要写一个程序实现自动备份,然后让定时任务软件帮你执行。

闹钟。。。。可以追女朋友。。。

3、怎样用。

(1)系统定时任务计划

1.不用管理员干预,系统自动执行。

2.也可以利用系统任务为管理员服务。

[root@oldboy ~]# ll /var/log/messages*

-rw-------. 1 root root  96594 Mar 21 12:40 /var/log/messages

-rw-------. 1 root root 485249 Mar 20 10:46 /var/log/messages-20190320

[root@oldboy ~]# ll /var/log/secure*

-rw-------. 1 root root 1430 Mar 21 12:50 /var/log/secure

-rw-------. 1 root root 2695 Mar 20 10:46 /var/log/secure-20190320

[root@oldboyedu /etc/cron.daily]# ll /etc/cron.daily/logrotate  /etc/logrotate.conf

-rwx------. 1 root root 219 Oct 31  2018 /etc/cron.daily/logrotate

-rw-r--r--. 1 root root 662 Jul 31  2013 /etc/logrotate.conf

按天切割日志,就可以用logrotate。

(2)用户定时任务计划

在Linux系统中,

cron是定时任务的软件名,

crond是服务进程名,真正实现定时任务服务。

crontab命令是用来设置定时任务规则的配置命令。

要想配置定时任务,首先启动crond服务。

systemctl start crond.service

systemctl stop crond.service

systemctl status crond.service

开启自启动:

systemctl disable crond.service

systemctl enable crond.service

-l l列表 查看已经设置的定时任务*

-e edit 编辑定时任务*

-u user 查看特定用户下定时任务

root:

crontab -l == cat /var/spool/cron/root

crontab -e == vim /var/spool/cron/root

编写定时任务的语法:

# 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

# |  |  |  |  |

# *  *  *  *  *  (command to be executed)

共六列:

第一列:分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

第六列:要执行的任务命令或程序

特殊符号:

*表示的 每或每一 的意思

00 23 * * * cmd

每天23点0分执行cmd

- 连续区间 1-10

00 8-23 * * * cmd

每天的8点到23点之间每个小时的0分

, 列举 1,2,3,4,8

00 1,2,3,4,8 * * * cmd

每天的1点2点3点4点8点执行任务

/n n是数字。

n代表自然数字,即“每隔n单位时间”,例如:每10分钟执行一次任务可以写成

*/10 * * * * cmd

每隔10分钟执行一次




生产环境下的定时Cron书写要领

要领1:为定时任务规则加必要的注释

要领2:所有的定时任务尽量都以脚本的形式执行

要领3:在执行的Shell脚本前加上/bin/sh

要领4:定时任务中命令或脚本的结尾加>/dev/null 2>&1

要领5:在指定用户下执行相关定时任务

要领6:生产任务计划程序中不要随意打印输出信息,有输出的想法去掉。

要领7:定时任务执行的脚本要存放到规范路径下

要领8:配置定时任务要规范操作过程,减少出错

要领9:定时任务脚本中程序命令及路径尽量用全路径

要领10:时间变量%号要用反斜线转义(只有定时任务里是命令时需要)

要领11:若脚本中调用了系统环境变量,要重新定义

要领12:出错或无法执行,就检查/var/log/cron日志 

你可能感兴趣的:(Linux系统定时任务)