当前位置: 移动技术网 > 科技>操作系统>Linux > 在Linux系统中简单地实现定时备份的方法

在Linux系统中简单地实现定时备份的方法

2018年07月21日  | 移动技术网科技  | 我要评论

运行一个简单的脚本

假设你有一个脚本叫:/usr/local/bin/myscript ,你想要每隔一小时就运行一次。
service 文件

第一步,创建一个service文件,根据你linux的发行版本放到相应的系统目录(在arch中,这个目录是/etc/systemd/system/ 或 /usr/lib/systemd/system)

myscript.service

   

复制代码
代码如下:
[unit]
description=myscript

[service]
type=simple
execstart=/usr/local/bin/myscript

注意,务必将type变量的值设置为"simple"而不是"oneshot"。使用"oneshot"使得脚本只在第一次运行,之后系统会认为你不想再次运行它,从而关掉我们接下去创建的定时器(timer)。
timer 文件

第二步,创建一个timer文件,把它放在第一步中service文件放置的目录。

myscript.timer

   

复制代码
代码如下:
[unit]
description=runs myscript every hour

[timer]
# 首次运行要在启动后10分钟后
onbootsec=10min
# 每次运行间隔时间
onunitactivesec=1h
unit=myscript.service

[install]
wantedby=multi-user.target

授权 / 运行

授权并运行的是timer文件,而不是service文件。

   

复制代码
代码如下:
# 以 root 身份启动定时器
systemctl start myscript.timer
# 在系统引导起来后就启用该定时器
systemctl enable myscript.timer

在同一个timer上运行多个脚本

现在我们假设你在相同时间想要运行多个脚本。这种情况,你需要在上面的文件中做适当的修改。
service 文件

创建你的service文件来运行你的脚本,但是在每个service 文件最后都要包含下面的内容:

   

复制代码
代码如下:
[install]
wantedby=mytimer.target

如果在你的service 文件中有一些依赖顺序,确保你使用description字段中的值具体指定after=something.service和before=whatever.service中的参数。

另外的一种选择是(或许更加简单),创建一个包装脚本来使用正确的顺序来运行命令,并在你的service文件中使用这个脚本。
timer 文件

你只需要一个timer文件,创建mytimer.timer,像我在上面指出的。
target 文件

你可以创建一个以上所有的脚本依赖的target文件。

mytimer.target

   

复制代码
代码如下:
[unit]
description=mytimer
# lots more stuff could go here, but it's situational.
# look at systemd.unit man page.

授权 / 启动

你需要将所有的service文件和timer文件授权。

   

复制代码
代码如下:
systemctl enable script1.service
systemctl enable script2.service
...
systemctl enable mytimer.timer
systemctl start mytimer.service

good luck.

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网