1、安装 cron
sudo apt-get install cron
2、查看cron状态
service cron status
● cron.service - Regular background program processing daemon
Loaded: loaded (/lib/systemd/system/cron.service; enabled; vendor preset: enabled)
Active: active (running) since 二 2022-05-10 11:39:52 CST; 2h 10min ago
Docs: man:cron(8)
Main PID: 28305 (cron)
CGroup: /system.slice/cron.service
└─28305 /usr/sbin/cron -f
3、创建一个定时服务
crontab -e (当前用户)
如果是第一次使用,会让你选择一个编辑器,如下:
Select an editor. To change later, run 'select-editor'.
1. /bin/ed
2. /bin/nano <---- easiest
3. /usr/bin/vim.basic
4. /usr/bin/vim.tiny
我个人习惯使用vim,所以选择3即可
Choose 1-4 [2]: 3
然后是 编辑内容,如:
# 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
37 03 * * * /disk/codes/s_auto_patch_sh
分 时 天 月 周 命令 -》*表示每天(周),像这里表示,每天的03:37 执行 /disk/codes/s_auto_patch_sh 脚本
PS:这里的执行脚本,有人说最好不要使用 带 . 的命名。好像有时候是会有莫名其妙的问题,好在linux并不在意后缀名。所以s_auto_patch.sh ,我命名成s_auto_patch_sh。
4、重启服务
sudo service cron start
5、其他
crontab -e 编辑创建一个定时服务
crontab -l 查看当前用户的定时任务
crontab -r 删除当前用户的定时任务