Linux 定时执行任务

crontab定时任务

crontab -e
# 每2小时清理一次caches
0 * * * * sh -c "echo 2 > /proc/sys/vm/drop_caches"

systemd定时任务

创建服务单元文件.service

sudo vim /etc/systemd/system/clear_cache.service

写入以下内容

[Unit]
Description=Clear system cache

[Service]
Type=simple
ExecStart=/sbin/echo 2 > /proc/sys/vm/drop_caches

创建定期任务.timer

sudo vim /etc/systemd/system/clear_cache.timer

写入内容

[Unit]
Description=Run clear_cache service every hour

[Timer]
OnCalendar=*-*-* */1:00:00
Persistent=true

[Install]
WantedBy=timers.target

启用配置

# 重新加载配置
sudo systemctl daemon-reload
# 系统重启自动启动
sudo systemctl enable clear_cache.timer
# 查看定时器状态
sudo systemctl status clear_cache.timer
posted on 2025-02-18 14:46  风惊庭前叶  阅读(12)  评论(0)    收藏  举报