Ubuntu 定时任务

 
 
一.cron相关命令
#重载cron
sudo service cron reload
 
#查看cron状态
service cron status
 
#查看cron pid
pidof cron 
 
#获取cron进程
pgrep cron
 
#启动cron服务
service cron start
 
#重启cron服务
sudo service cron restart
 
#安装cron服务
apt-get install cron
 
 
二.参数介绍
-u user 指定用户
-e 编辑某个用户的计划任务文件,若不指定用户,默认编辑当前用户的计划任务文件
-l 显示某个用户的计划任务文件,若不指定用户,默认显示当前用户的计划任务文件
-r 删除某个用户的计划任务文件,若不指定用户,默认删除当前用户的计划任务文件
-i 在删除之前推送确认提示
 
 
三.计划任务查看
#编辑用户 foo 的计划任务文件
crontab -u foo -e 
 
#编辑当前用户的计划任务文件
crontab -e 
 
#显示用户 foo 的计划任务文件
crontab -u foo -l 
 
#显示当前用户的计划任务文件
crontab -l 
 
#删除当前用户的计划任务文件
crontab -r 

任务计划的语法格式:
m h dom mon dow command
0-59 0-23 1-31 1-12 0-7 command

 
四.说明
  • m: 表示分钟
  • h: 表示小时
  • dom: 表示日期
  • mon: 表示月份
  • dow: 表示星期
  • command: 预执行的命令

另外需要使用一些特殊符号实现灵活的配置:

  • * 代表所有值
  • / 代表“每”
  • - 代表范围
  • , 分割数字
 
五.示例
## 指定具体执行时间
2 * * * * ls #每个小时的第2分钟执行一次 ls 命令
30 7 * * * ls #每天7:30执行一次 ls 命令
30 20 * * 2 ls #每周二,20:30执行一次 ls 命令(0和7表示星期天)

## 指定间隔时间
*/2 * * * * ls #每隔2分钟执行一次 ls 命令
00 */1 * * *  #每隔一小时执行一次
* */1 * * * #错误的每隔一小时执行一次,事实上每分钟执行一次
## 指定时间段
30 7 3-6 * * ls #每个月的3,4,5,6号的7:30分各执行一次 ls 命令

## 指定多个时间
30 7 3,6 * * ls #每月的3号和6号的7:30分各执行一次 ls 命令 

##指定目录下的所有脚本
30 7 * * * run-parts /home #每天7:30运行 /home 目录下的所有脚本

 
 
六.一个实际的定时任务(以下为 crontab -e 命令打开的文件,最后一行是我们加入的任务)
# Edit this file to introduce tasks to be run by cron. 

# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task

# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.

# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).

# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/

# For more information see the manual pages of crontab(5) and cron(8)

# m h dom mon dow command
*/2 * * * * echo "Hello World" >> /home/cron_test 
原文地址:https://www.cnblogs.com/sea-stream/p/9781427.html