引言
设想一个场景,每天8点需要发送一封邮件,或者对数据进行封装存储到仓库,定期备份数据,在Windows下由GUI的任务计划,而Linux可以使用cron,但是有些系统不内置cron需要手动安装。
安装cron
我没有手动安装,因为我的系统已经内置了cron,因为开发环境我选择的是Ubuntu,所以使用apt-get进行包管理,如果没有可以使用apt-get install cron 来安装
定时任务
设置定时任务,可以通过crontab -e 进行编辑任务列表, 编辑器由你的默认编辑器启动, 比如vim, 里面可能什么都没有, 不要慌, 写就完了.
格式
我们可以使用cat /etc/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
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
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 )
#
在线测试: https://crontab.guru/
样例
0 */3 * * * 每三个小时执行一次
*/2 * * * * 每2分钟执行一次
2 * * * * 每小时的第二分钟执行一次
30 6 * * * 每天六点半执行一次
3 2 1 * * 每月1号两点三分执行一次
3 2 */10 * * 每隔10天的两点三分执行一次
0 0 5 1-2 * 一二三月的五号零时零分执行一次
生效
通过服务重启进行即时生效, ubuntu服务为cron,而其他的可能是crond.

评论 0
还没有评论,来说点什么吧。