在 Bash 中每秒运行一次命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9299704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run command every second in Bash?
提问by Egor Sazanovich
I want to write some image downloader and assign it on bash. What I have and what I need:
我想编写一些图像下载器并在 bash 上分配它。我有什么和我需要什么:
I have:
我有:
- Command, which works fine (something like
wget http://mywebcam.com/image.jpg -O /var/cam/Image.jpg
) Root rights
Fast Internet line between my server and my webcam
- 命令,工作正常(类似于
wget http://mywebcam.com/image.jpg -O /var/cam/Image.jpg
) 根权限
我的服务器和我的网络摄像头之间的快速互联网线路
What I need:
我需要的:
Download image from camera every second*(sleep 1?)* and rewrite it localy (my command do it well)Run this script at once and don't worry about restart (I think I need to create file with bash commands and run it once + set crontab work "on reboot" to this file, right?)
每秒从相机下载图像*(睡眠 1?)* 并在本地重写(我的命令做得很好)立即运行此脚本,不要担心重启(我想我需要使用 bash 命令创建文件并运行它once + set crontab work“on reboot”到这个文件,对吧?)
Maybe there's someone who knows what should I to do?
也许有人知道我该怎么做?
回答by William Pursell
If you want to run a command at one second intervals (one second between the end of one command and the beginning of the next, which is not the same as running every second), just do:
如果你想每隔一秒运行一个命令(一个命令结束和下一个命令开始之间的一秒,这与每秒运行不同),只需执行以下操作:
while sleep 1; do cmd; done
If you want that to start on reboot, the method will depend on your system.
如果您希望在重新启动时启动,该方法将取决于您的系统。
回答by while
The command watch
will do this for you straight up. It also displays the result in a nice way.
该命令watch
将直接为您执行此操作。它还以一种很好的方式显示结果。
$ watch -n 1 date
Substitute date
for your command. The -n
option specifies the interval in seconds.
代替date
您的命令。该-n
选项以秒为单位指定间隔。
回答by Newerth
To add my two cents to this... If the cron's one minute interval is too long for you, you can take advantage of the systemd's capability to restart services repeatedly.
再加上我的两分钱...如果 cron 的一分钟间隔对您来说太长,您可以利用 systemd 的功能重复重新启动服务。
[Unit]
Description=Poll something each second
[Service]
Type=simple
ExecStart=/opt/poller/poll.sh
Restart=always
RestartSec=1
StartLimitInterval=0
[Install]
WantedBy=multi-user.target
I know it's a messy and sort of "never ever do this" approach. But it works perfectly an is fairly simple to set up.
我知道这是一种凌乱的“永远不要这样做”的方法。但它工作得很好并且设置起来相当简单。