centos7中利用systemd.timer設置定時時間同步

背景

centos7安裝在windows中的vmware虛擬機中,一旦windows進入睡眠狀態,則centos7也會休眠且系統時間會停止,因此centos7的系統時間會逐步比windows慢,想到用定時任務的方式去同步互聯網時間,以保持centos7的準確。大家都很熟悉crontab了,但其只能精確到分鐘級別,查閱資料發現systemctld也有定時任務功能,於是進行了嘗試。

實現

  1. 編寫同步時間腳步custom.sh
#首先,進入到/usr/lib/systemd/system目錄
#然後,創建custom.sh腳步,內容如下:

#!/bin/bash
echo "sync time starting...";
ntpdate 1.cn.pool.ntp.org;hwclock -w;
echo "sync time completed.";
  1. 創建service單元custom.service
[Unit]
Description=service of timer created by daijiguo

[Service]
Type=simple
ExecStart=/usr/lib/systemd/system/custom.sh
  1. 創建timer單元custom.timer
[Unit]
Description=timer defined by daijiguo

[Timer]
#設置定時任務
OnCalendar=*-*-* 12:00:00
Unit=custom.service

[Install]
WantedBy=multi-user.target

4.設置custom.service和custom.timer開機啓動

#開機自啓
systemctl enable custom.service
systemctl enable custom.timer
#啓動單元
systemctl start custom.service
systemctl start custom.timer

注意點

  1. 如果custom.service不設置成開機自啓,且不啓動,單獨啓動custom.timer,則腳本只會運行一次然後通過systemctl status custom.timer發現狀態爲elapsed,原因不明,有知道同學可以指點一下。因此custom.service的啓動和開機自啓不可缺少。
  2. 在custom.timer中創建定時任務的時候,如果要每隔一定週期運行一次任務,則使用OnUnitActiveSec=進行配置;如果要使用跟複雜的表達式,則使用OnCalendar=進行配置,切不可亂用,具體可以參考官方手冊。

參考:
https://www.freedesktop.org/software/systemd/man/systemd.time.html#
https://www.linuxidc.com/Linux/2019-05/158599.htm
https://cloud.tencent.com/developer/article/1412404
https://www.cnblogs.com/whymoney1000/p/11059803.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章