CentOS 使用 Cronie 实现定时任务

CentOS 使用 Cronie 实现定时任务

一、简介

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 41 14:16 create.sh
-rw-r--r-- 1 root root   34 41 14:13 timestamp_20240401141301.txt
-rw-r--r-- 1 root root   34 41 14:14 timestamp_20240401141401.txt
-rw-r--r-- 1 root root   34 41 14:15 timestamp_20240401141501.txt
-rw-r--r-- 1 root root   34 41 14:16 timestamp_20240401141601.txt
-rw-r--r-- 1 root root   34 41 14:17 timestamp_20240401141701.txt
-rw-r--r-- 1 root root   34 41 14:18 timestamp_20240401141801.txt
-rw-r--r-- 1 root root   34 41 14:19 timestamp_20240401141901.txt
-rw-r--r-- 1 root root   34 41 14:20 timestamp_20240401142001.txt
-rw-r--r-- 1 root root   34 41 14:21 timestamp_20240401142101.txt
-rw-r--r-- 1 root root   34 41 14:22 timestamp_20240401142201.txt
-rw-r--r-- 1 root root   34 41 14:23 timestamp_20240401142301.txt
-rw-r--r-- 1 root root   34 41 14:24 timestamp_20240401142401.txt
-rw-r--r-- 1 root root   34 41 14:25 timestamp_20240401142501.txt
-rw-r--r-- 1 root root   34 41 14:26 timestamp_20240401142601.txt
-rw-r--r-- 1 root root   34 41 14:27 timestamp_20240401142701.txt
-rw-r--r-- 1 root root   34 41 14:28 timestamp_20240401142801.txt
-rw-r--r-- 1 root root   34 41 14:29 timestamp_20240401142901.txt
-rw-r--r-- 1 root root   34 41 14:30 timestamp_20240401143001.txt

3、其它

注意权限问题!

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值