我用 LinuxLinux学习|Gentoo/Arch/FreeBSDLinux

linux定时执行脚本——按照你期望的方式

2019-10-11  本文已影响0人  Mx_php

如何每分钟执行一个命令?
如何让脚本只在工作日执行?
如何让脚本只在上班时间执行?
元旦当天的8点执行任务怎么做?

```* * * * * /var/shell/test.sh```  // 这个五个星代表什么意思?
```10 * * * * /var/shell/test.sh``` // 这是代表每天的xx点10分执行脚本还是每10分钟执行一次?
```10 2,3,5,12 * * * /var/shell/test.sh``` // 这逗号又是什么意思?
```10 8-17 * * 1-5 /var/shell/test.sh``` // 代表工作日8-17点,每10分钟执行一次脚本吗?
```*/5 */2 * * * /var/shell/test.sh``` // 这么写对不对?

本文用于解决如上问题,记住以上表达式的含义。并简单说明crontab命令。

linux系统用于执行计划任务的命令,命令行输入如下命令,

cat /etc/crontab

输出如下结果:


[root@localhost cron]# cat /etc/crontab

SHELL=/bin/bash

PATH=/sbin:/bin:/usr/sbin:/usr/bin

MAILTO=root

HOME=/

# 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

说明

配置

前四行是用来配置crond任务运行的环境变量:

注释及参数说明

上面代码返回的注释标识了命令格式及参数说明。

crontab命令格式如下:

* * * * * user-name command to be executed

分钟(0-60)、小时(0-23)、天(1-31)、月(1-12)、星期(0-6);

命令参数的特殊符号

(*) :代表所有可能的值

(,) :用逗号隔开的值指定对应字段的列表范围,例如:“1,3,5”在月份中则限制执行命令在1 3 5 月执行;

(-) :表示一个整数范围,例如“2-6”表示“2,3,4,5,6”;

(/) :指定时间的间隔频率,例如“0-23/2”表示每两小时执行一次。同时 / 可以和 * 一起使用,例如 */10,如果用在minute字段,表示每十分钟执行一次。

crond 服务

安装

yum install crontabs

操作说明:

/sbin/service crond start //启动服务

/sbin/service crond stop //关闭服务

/sbin/service crond restart //重启服务

/sbin/service crond reload //重新载入配置

查看服务状态:

service crond status

手动启动:

service crond start

查看服务自启动情况

ntsysv

开机自动启动命令:

chkconfig –level 35 crond on

crontab 用法


usage:  crontab [-u user] file

crontab [-u user] [ -e | -l | -r ]

(default operation is replace, per 1003.2)

-e  (edit user's crontab)

-l  (list user's crontab)

-r  (delete user's crontab)

-i  (prompt before deleting user's crontab)

-s  (selinux context)

例如我输入crontab -e后出现如下我自己的计划任务


*/5 * * * * /xxx1.sh // 每五分钟执行1次

0 3 * * * /xxx2.sh  // 每天3点执行1次

0 4 * * * /xxx3.sh // 每天4点执行1次

上一篇 下一篇

猜你喜欢

热点阅读