crontab定时任务

来源:互联网 发布:js递归调用方法 编辑:程序博客网 时间:2024/05/16 16:09

有定时执行一次和定时重复执行两种定时任务

使用at命令定时执行一次任务

  1. 确认at daemon是否启动
# ps -ef | grep atdroot 8231 1 0 18:10 ? 00:00:00 /usr/sbin/atd

如果没有启动之

# /etc/init.d/atd start
  1. 定时执行一个脚本
at -f shellscript.sh -v 18:30

意思是在今天下午6点时候执行shellscript.sh脚本
还可以这样使用at命令:

# at -f shellscript.sh 10pm tomorrow# at -f shellscript.sh 2:50 tuesday# at -f shellscript.sh 6:00 july 11# at -f shellscript.sh 2:00 next week

at命令只会执行脚本一次,如果需要重复执行,需要使用cron

使用cron定时执行

先看看当前用户有什么定时任务

crontab -l

如果有的话会输出类似下面的东西:

0 6 * * * /opt/scripts/backup_script.sh

具体啥意思呢,看下面一目了然。

0  6  *  *  * /opt/scripts/backup_script.sh|  |  |  |  ||  |  |  |  |________________ day of week (Sunday=0)|  |  |  |__________________ month of year|  |  |____________________ day of month|  |______________________ hour of day|________________________ minute of hour

意思是每天6点钟执行backup_script.sh脚本。
上面每个域中如果有多个值,使用逗号分隔。比如:

0 1,9,17 * 2,11 * /opt/scripts/db_backup_script.sh

每个域还可以细分时间间隔:

*/5 * * * * /bin/bash /pathto/task.sh

表示每隔5分钟执行一次。
同理:

* */5 * * * /bin/bash /pathto/task.sh

表示每隔5小时。

添加定时任务

使用命令:

crontab -e

进入一个编辑器,输入下面一行:

45 15 * * 1 /opt/scripts/script.sh

保存退出编辑器,那么就完成了一个定时任务:每周一下午3:45执行脚本script.sh

0 0