在CentOS中,你可以使用systemd的timer单元来设置相对时间的定时任务。以下是创建一个相对时间定时任务的步骤:
my-service.service的文件,内容如下:[Unit]
Description=My custom service
[Service]
ExecStart=/usr/bin/echo "Hello, World!"
将此文件保存到/etc/systemd/system/目录下。
my-timer.timer的文件,内容如下:[Unit]
Description=Run my-service.service every 1 hour
[Timer]
OnCalendar=*-*-* *:00:00
Persistent=true
Unit=my-service.service
[Install]
WantedBy=timers.target
在这个例子中,我们设置了定时器每小时执行一次my-service.service。OnCalendar字段定义了定时器的触发时间,这里设置为每天的整点。你可以根据需要修改这个字段,例如设置为相对时间,如1h表示1小时后。
systemd配置:sudo systemctl daemon-reload
sudo systemctl enable --now my-timer.timer
现在,你的定时任务已经设置好了。你可以使用以下命令查看定时器的状态:
sudo systemctl list-timers --all
或者查看特定定时器的详细信息:
sudo systemctl status my-timer.timer
这样,你就成功地在CentOS中设置了一个相对时间的定时任务。