linux之时间服务器

序

在项目开发中,各个模块的时间同步是一个重要的机制;那么如何在linux上搭建时间服务器呢?并且客户端怎么与服务器进行时间同步呢?

时间服务器搭建

linux中有两种时间服务器: ntp服务器和chrony服务器

1.ntp服务器

1.1 安装

bash 复制代码
apt install ntp

1.2 配置

配置文件一般在/etc/ntp.conf;添加如下内容(根据自己的情况配置):

添加内容
bash 复制代码
#本地时间作为同步时间源
server 127.127.1.0 prefer
# 本地服务器的stratum大小不能超过16;
fudge 127.127.1.0 stratum 8
# 允许192.168.*.*的IP使用该时间服务器;
restrict 192.168.0.0 mask 255.255.0.0 nomodify
#允许任何人来同步;
restrict default nomodify notrap
# 将时间同步到硬件时钟
SYNC_HWCLOCK=yes
修改内容
bash 复制代码
#注释掉这几行
#pool 0.ubuntu.pool.ntp.org iburst
#pool 1.ubuntu.pool.ntp.org iburst
#pool 2.ubuntu.pool.ntp.org iburst
#pool 3.ubuntu.pool.ntp.org iburst

# Use Ubuntu's ntp server as a fallback.
#pool ntp.ubuntu.com

1.3 重启服务器

修改完配置文件需要重启服务器

bash 复制代码
systemctl restart ntp#重启
systemctl start ntp#启动
systemctl stop ntp#停止

2.chrony服务器

1.1 安装

bash 复制代码
apt install chrony

1.2 配置

配置文件一般在/etc/chrony/chrony.conf;添加如下内容(根据自己的情况配置):

添加内容
bash 复制代码
local stratum 10
allow 192.168.0.0/24#允许192.165*.*的ip访问
修改内容
bash 复制代码
#注释掉
#pool ntp.ubuntu.com        iburst maxsources 4
#pool 0.ubuntu.pool.ntp.org iburst maxsources 1
#pool 1.ubuntu.pool.ntp.org iburst maxsources 1
#pool 2.ubuntu.pool.ntp.org iburst maxsources 2

1.3 重启服务器

修改完配置文件需要重启服务器

bash 复制代码
systemctl restart chronyd#重启
systemctl start chronyd#启动
systemctl stop chronyd#停止

注意:有时候执行上面的命令提示:chronyd.service not found;具体原因不清楚;可以直接运行:

bash 复制代码
chronyd &

客户端同步

执行命令进行同步,二者本质就是进行ntp同步,使用相同的命令:

bash 复制代码
ntpdate -u 服务器ip

没有安装的话进行安装

bash 复制代码
apt install ntpdate

成功之后是这个样子

bash 复制代码
# ntpdate -u 192.168.0.105
14 Nov 10:31:08 ntpdate[10150]: adjust time server 192.168.0.105 offset 0.018081 sec

问题记录

问题1

想要实现1分钟同步依次时间

bash 复制代码
*/1 * * * *  ntpdate -u 11.64.13.250

ntpdate -u 11.64.13.250是能在终端直接执行,并且同步成功的;但是加到定时器任务队列中就不行;等还久没一点反应;

解决方案也很简单:ntpdate命令使用绝对路径就可以了;为了保险起见前面使用sudo以管理员权限运行;

bash 复制代码
*/1 * * * * sudo /usr/sbin/ntpdate -u 11.64.13.250;

问题2

时钟同步后,重启ubuntu系统时间又恢复以前的时间

如果是linux系统(烧写uboot kernel 文件系统等)需要同步本地时间到硬件时钟;使用命令:

bash 复制代码
sudo hwclock --systohc
sudo hwclock -w

如果是ubuntu系统:

bash 复制代码
timedatectl set-local-rtc 1
sudo hwclock -w

#备注:
#timedatectl set-local-rtc 1: 设置硬件时钟为本地时间
#timedatectl set-local-rtc 0: 设置硬件时钟为协调世界时间
相关推荐
小羊没烦恼!8 分钟前
T-SQL查询进阶--理解SQL SERVER中的分区表
服务器·开发语言·前端·javascript·html
Zucker n11 分钟前
一款适合研究生科研工作安排的日历
linux·数据库·python
爱吃香菜的初学者25 分钟前
十六.Linux——多线程(2)
linux·运维·开发语言
xixingzhe242 分钟前
Nginx 看懂请求耗时瓶颈
服务器·前端·nginx
荒--2 小时前
Ubuntu软件包查询,弹框下载文件
运维·服务器·ubuntu
‎ദ്ദിᵔ.˛.ᵔ₎2 小时前
Linux:对有关 SIGCHLD 的深层理解
linux·运维·服务器
aichitang20242 小时前
QCU 2.0.0:补齐 Windows、Linux 与 GNOME Wayland
linux·运维·windows·ai·agent·ai编程
Lv_沐曦2 小时前
Linux 上的Web文件管理器-filebrowser
linux·运维·服务器
NGINX开源社区2 小时前
与我们交流:NGINX Gateway Fabric 与 NGINX Ingress Controller 社区会议
java·服务器·前端