CentOS 使用 Cronie 实现定时任务
文章目录
- CentOS 使用 Cronie 实现定时任务
- 一、简介
- 二、基本使用
- 1、常用命令
- 2、使用示例
- 第一步:创建脚本`/home/create.sh`
- 第二步:添加定时任务
- 第三步:重启 cronie 服务
- 额外:查看 cronie 运行状态
- 定时任务执行结果参考
- 3、其它
一、简介
Cronie 是 CentOS 中用于配置定时任务的工具。它可以周期性地执行指定的命令或脚本。Cronie 由两个部分组成:
- crond:守护进程,负责检查和执行定时任务。
- crontab:配置文件,用于定义定时任务。
二、基本使用
1、常用命令
# 安装 cronie
sudo yum install cronie# 启动 cron 服务
sudo systemctl start crond# 重启 cron 服务
sudo systemctl restart crond# 查看 cron 状态
sudo systemctl status crond# 查看 cron 任务
crontab -l# 编辑/删除 cron 任务
# 要删除一个 `cron` 任务,你可以编辑 `/etc/crontab` 文件或者 `/etc/cron.d/` 目录下的文件,或者使用 `crontab -e` 命令来编辑当前用户的cron任务。
crontab -e
2、使用示例
第一步:创建脚本/home/create.sh
#!/bin/bash
# 创建一个包含当前时间戳的.txt文件
TIMESTAMP=$(date '+%Y%m%d%H%M%S')
FILENAME="timestamp_${TIMESTAMP}.txt"
echo "Current timestamp: ${TIMESTAMP}" > "/home/${FILENAME}"
第二步:添加定时任务
# 打开任务编辑器
crontab -e# 命令内容
* * * * * /home/create.sh
第三步:重启 cronie 服务
sudo systemctl restart crond
额外:查看 cronie 运行状态
sudo systemctl status crond
定时任务执行结果参考
[root@VM-0-11-centos home]# ls -l
总用量 80
-rwxrwxrwx 1 root root 193 4月 1 14:16 create.sh
-rw-r--r-- 1 root root 34 4月 1 14:13 timestamp_20240401141301.txt
-rw-r--r-- 1 root root 34 4月 1 14:14 timestamp_20240401141401.txt
-rw-r--r-- 1 root root 34 4月 1 14:15 timestamp_20240401141501.txt
-rw-r--r-- 1 root root 34 4月 1 14:16 timestamp_20240401141601.txt
-rw-r--r-- 1 root root 34 4月 1 14:17 timestamp_20240401141701.txt
-rw-r--r-- 1 root root 34 4月 1 14:18 timestamp_20240401141801.txt
-rw-r--r-- 1 root root 34 4月 1 14:19 timestamp_20240401141901.txt
-rw-r--r-- 1 root root 34 4月 1 14:20 timestamp_20240401142001.txt
-rw-r--r-- 1 root root 34 4月 1 14:21 timestamp_20240401142101.txt
-rw-r--r-- 1 root root 34 4月 1 14:22 timestamp_20240401142201.txt
-rw-r--r-- 1 root root 34 4月 1 14:23 timestamp_20240401142301.txt
-rw-r--r-- 1 root root 34 4月 1 14:24 timestamp_20240401142401.txt
-rw-r--r-- 1 root root 34 4月 1 14:25 timestamp_20240401142501.txt
-rw-r--r-- 1 root root 34 4月 1 14:26 timestamp_20240401142601.txt
-rw-r--r-- 1 root root 34 4月 1 14:27 timestamp_20240401142701.txt
-rw-r--r-- 1 root root 34 4月 1 14:28 timestamp_20240401142801.txt
-rw-r--r-- 1 root root 34 4月 1 14:29 timestamp_20240401142901.txt
-rw-r--r-- 1 root root 34 4月 1 14:30 timestamp_20240401143001.txt
3、其它
注意权限问题!