crontab定时执行程序

概述

cron是linux中的一个定时执行工具,可让系统在特定的时间自动执行特定的任务,如数据库备份、日志分析等。

crontab 是一个包含一系列定时任务命令的文本文件。该文件使用crontab 命令进行编辑。文件中的命令由cron在后台执行。

系统中的每个用户(包括root)都拥有一个crontab文件,无论该用户是否登录系统,cron都会检测用户的crontab文件。

crontab的在线帮助文档可以通过man crontab 查看,也可以通过OpenGroup 进行查看。

使用方法

编辑crontab文件

编辑用户crontab命令: crontab -e
第一次使用会弹出选择编辑器的对话框,如图:
choose editor

这里我选择第3个,使用vim打开crontab文件进行编辑。

输入想要执行的定时任务命令,然后保存后退出。

crontab 文件格式的帮助文档使用man 5 crontab 命令查看。

如果要执行需要sudo权限的程序,相应的命令需要添加到root crontab 文件中,编辑该文件的命令:sudo crontab -e

crontab 命令行

crontab 文件中每行代表一条执行命令,每条命令的格式由两部分组成:时间-日期域,待执行命令。每条命令以换行符’\n’结束。

其中,时间-日期域中包含5个域,各个域之间是以空格为分割符的。这5个域分别为:

1 2 3 4 5
分钟(0-59) 小时(0-23) 日期(1-31) 月(1-12) 周(0-6,0代表周日)
  • 例子1:
    01 04 1 1 1 /usr/bin/somedirectory/somecommand
    该例子将运行/usr/bin/somedirectory/somecommand 命令,运行时间为上午4:01,运行日期为1月1日1月的每个周一

  • 例子2:
    01 04 * * * /usr/bin/somedirectory/somecommand
    该例子表示:在每天的4:01运行/usr/bin/somedirectory/somecommand
    (* 表示一个域中的所有值)

  • 例子3:
    01,31 04,05 1-15 1,6 * /usr/bin/somedirectory/somecommand
    该例子表示:在1月和6月的1~15号的上午4:01、4:31、5:01和5:31时间点执行命令/usr/bin/somedirectory/somecommand

也可以设定在一个时间单元内多次运行脚本

  • 例子
    每10分钟运行一次脚本:
    */10 * * * * /usr/bin/somedirectory/somecommand
    等价于:
    0,10,20,30,40,50 * * * * /usr/bin/somedirectory/somecommand

cron也提供了一些特殊字符串用于替代上述的5个时间-日期域:

string meaning
@reboot Run once, at startup.
@yearly Run once a year, “0 0 1 1 *”.
@annually (same as @yearly)
@monthly Run once a month, “0 0 1 * *”.
@weekly Run once a week, “0 0 * * 0”.
@daily Run once a day, “0 0 * * *”.
@midnight (same as @daily)
@hourly Run once an hour, “0 * * * *”.

@reboot /path/to/execuable1
在系统启动时执行/path/to/execuable1

参考文献

CronHowto

猜你喜欢

转载自blog.csdn.net/yingyujianmo/article/details/51893409