STC214/Ubuntu - crontab 命令定时执行任务

Created 30 Jun 2020 Modified 22 Sep 2023

处理大规模数据集时,需要等待的时间有时会很久,为了能充分利用晚上时间,发现 Ubuntu 的 crontab 服务是可以定时执行任务的.

  1. crontab 服务启动

Ubuntu 16.04 默认有 cron,如果没有,则进行安装:

sudo apt install cron

查看 cron 服务是否启动:

pgrep cron

若输出了pid,如 883,则 cron 服务已启动.

若没有任何输出,则cron服务未启动,需手工启动:

service cron start

  1. crontab 命令说明

cron 的任务计划保存在 /etc/crontab 文件中,文件内容如:

/etc/crontab: system-wide crontab

Unlike any other crontab you don’t have to run the `crontab'

command to install the new version when you edit this file

and files in /etc/cron.d. These files also have username fields,

that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

m h dom mon dow user command

17 * * * * root cd / && run-parts –report /etc/cron.hourly
25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts –report /etc/cron.daily )
47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts –report /etc/cron.weekly )
52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts –report /etc/cron.monthly )

可以通过 crontab命令进行任务管理:

编辑用户username 的计划任务文件

crontab -u username -e

显示某个用户的计划任务文件; 默认为当前用户

crontab -l
crontab -u username -l

设置定时任务, 编辑某个用户的计划任务文件;默认为当前用户

crontab -e

删除某个用户的计划任务文件;默认为当前用户

crontab -r

  1. 添加任务计划

进入 crontab编辑模式:

crontab -e

进行任务添加.

也可以直接编辑 /etc/crontab 文件,在尾部添加计划任务.

crontab 任务计划的语法格式:

m h dom mon dow user command

分 时 日 月 周 用户名 计划任务命令

17 * * * * root cd / && run-parts –report /etc/cron.hourly

第1列 - 分钟1~59 每分钟用 * 或者 */1 表示

第2列 - 小时1~23(0表示0点)

第3列 - 日期1~31

第4列 - 月份1~12

第5列 - 星期0~6(0表示星期天)

第6列 - 用户名

第7列 - 计划执行的任务命令

其中,使用run-parts 运行指定目录下的所有脚本.(编辑的脚本必须包含 #!/bin/bash). 如:

每天 23:30 运行 /home/my_scripts/ 目录下的所有脚本

30 23 * * * run-parts /home/my_scripts/

更多计划设置,如:

每晚的 22:30 执行 cd /home/username/

30 22 * * * cd /home/username/

每月5,15,25日的 6:30 执行 ls

30 6 5,15,25 * * ls

每周六、周日的 21:25 执行 cd /opt/

25 21 * * 6,0 cd /opt/

每天3:00 至 6:00 之间每隔 30 分钟 执行 ls

0,30 3-6 * * * ls

每星期六的 23:00 执行 cd /home/username/

0 23 * * 6 cd /home/username/

每一小时 执行一次 ls

0 */1 * * * ls

23:00 至 7:00,每隔一小时 执行 ls

0 23-7/1 * * * ls

每月 7 号、每周二到周五的 23:00 执行 ls

0 23 4 * tue-fri ls

1 月 1 号的 1:00 执行 cd /home/username/

0 1 1 jan * cd /home/username/

每个小时的第 20 分钟执行一次 ls

20 * * * * ls

每天 8:30 执行 cd /home/username/

30 8 * * * cd /home/username/

每隔20分钟执行一次 ls

*/20 * * * * ls

注:

  • 表示所有值
    / 表示“每”
  • 表示区间范围
    , 表示分割数字

例如:每一分钟执行一次字符串 “Hello World” 打印输出到 /home/username/log.txt 文件的计划任务.

*/1 * * * * echo “Hello World” » /home/username/log.txt

*/1 * * * * username echo “Hello World” » /home/username/log.txt

原文:https://www.aiuai.cn/aifarm747.html

Gitalking ...