«

Linux定时任务/计划任务

时间:2023-3-12 17:39     作者:wen     分类: Linux


[TOC]

是为了简化系统管理员对于一些固定的/重复的/有规律的任务提供的一种服务, 从而实现自动化的一些任务, 解放管理员, 提示工作效率。

安全领域、运维领域、定时任务、脚本、自动化、端口保活、故障处理

定时任务服务对应的进程名称叫做Crond服务, 会定时/周期性的检查系统中是否有需要指定的任务/工作计划。

Cron(d)是Linux系统中以后台进程模式, 并且每分钟检查一次指定的任务是否需要运行。

定时任务的种类

crond服务

安装 yum install cronie

atd服务

临时的/运行一次

anacron服务

非7*24小时运行的服务器上

定时任务的分类

系统定时任务

  1. /etc/cron.daily 每天执行
  2. /etc/cron.hourly 每小时执行
  3. /etc/cron.monthly 每月执行
  4. /etc/cron.weekly 每周执行
  5. /etc/cron.deny 拒绝定时任务(黑名单)
  6. /etc/crontab 定时任务配置文件
  7. /var/log/cron-20230312 日志

典型的有日志分割, 定时任务+logrotate; 数据库更新, 定时任务+mlocate, 执行updatedb

用户定时任务

定时任务相关文件

  1. /var/log/cron 定时任务日志文件
  2. /etc/deny 配置文件
  3. /var/spool/cron 配置文件, 每分钟都会查看该路径下, 系统用户和root命令的定时任务

如何来使用定时任务

crontab命令
参数:

定时任务中的特殊符号

# 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

/ 表示间隔 * */1 * * * 每个一小时

xx-yy 表示一段 17-18

, x和y

注意: 集群/同步时间/NTP的问题

案例

  1. 设置一个定时任务, 每天早上8点30分钟执行 updatedb
    • 30 8 * * * updatedb
  2. 每天早上4点00分 /root/backup.sh增量备份
    • 00 04 * * * /root/backup.sh
  3. 每周六凌晨1点10分, 重启httpd服务
    • 10 01 * * 6 systemctl restart httpd
  4. 每周六和周日凌晨1点10分, 重启httpd服务
    • 10 01 * * 6,0 systemctl restart httpd
  5. 每个月1号10号20号, 下午04点45分重启httpd服务
    • 45 16 1,10,20 * * systemctl restart httpd
  6. 每隔一小时重启httpd
    • * */1 * * * systemctl restart httpd
  7. 每月4号与周一到周三晚上11点重启httpd
    • 00 23 4 * 1-3 systemctl restart httpd

标签: linux