前言

作为一个linux深度爱好者,当你使用python或者shell时,能估计好运行时间,想让程序运行完以后,换个参数继续运行,这个时候你就可以去睡觉或者出去玩了~如果能定时执行,是不是很灵性的操作

crontab命令简介

Linux crontab 是用来定期执行程序的命令。当安装完成操作系统之后,默认便会启动此任务调度命令。
crond 命令每分钟会定期检查是否有要执行的工作,如果有要执行的工作便会自动执行该工作。注意:新创建的 cron 任务,不会马上执行,至少要过 2 分钟后才可以,当然你可以重启 cron 来马上执行

使用方式

1
2
crontab -e  # 编辑cron任务
# 你会看到下面的注释,把这些都删了,输入你要执行的指令
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 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/
1
2
3
# 将这行指令输入刚才的编辑框里
30 5 * * * ls # 指定每天的 5:30 执行ls命令
# 保存退出 :wq
1
2
crontab -l  # 查看所有的调度任务
crontab -r # 删除所有的调度任务

时间格式如下:

1
f1 f2 f3 f4 f5 program
  • 其中 f1 是表示分钟,f2 表示小时,f3 表示一个月份中的第几日,f4 表示月份,f5 表示一个星期中的第几天。program 表示要执行的程序。
  • 当 f1 为 * 时表示每分钟都要执行 program,f2 为 * 时表示每小时都要执行程序,其余类推
  • 当 f1 为 a-b 时表示从第 a 分钟到第 b 分钟这段时间内要执行,其余类推
  • 当 f1 为 */n 时表示每 n 分钟个时间间隔执行一次,其余类推
  • 当 f1 为 a, b, c,… 时表示第 a, b, c,… 分钟要执行,其余类推

可以将你运行的python脚本和需要输入的参数封装成shell脚本,然后传给crontab即可定时运行,笔者正在使用,很香,参数调整好,让机器自己去跑就行,这时,你就可以去找小姐姐玩耍了

本文为了解决问题实时记录,更多问题和细节见-----菜鸟教程