crontab 示例
Today we will look into crontab example to execute a script every 5 minutes.
今天,我们将研究crontab示例以每5分钟执行一次脚本。
Crontab示例 (Crontab example)
Recently I installed memcached server on CentOS operating system to use as a caching mechanism for my VBulletin forum. To make sure that it’s running always, I wrote a shell script to check the process status and restart if it’s not running. Now to make sure this script executes at a specific interval, I used crontab.
最近,我在CentOS操作系统上安装了memcached服务器,以用作我的VBulletin论坛的缓存机制。 为了确保它始终在运行,我编写了一个Shell脚本来检查进程状态,如果没有运行则重新启动。 现在,要确保此脚本以特定的间隔执行,我使用了crontab 。
Crontab示例Shell脚本 (Crontab Example Shell Script)
The shell script is extendable and you can write a similar script to restart any service or process in unix systems.
Shell脚本是可扩展的,您可以编写类似的脚本来重新启动UNIX系统中的任何服务或进程。
Here is the shell script to auto restart service that I am using in my crontab example.
这是我的crontab示例中使用的自动重启服务的Shell脚本。
memcached_restart.sh
memcached_restart.sh
#!/bin/bash ps -eaf | grep 11211 | grep memcached # if not found - equals to 1, start it if [ $? -eq 1 ] then /usr/local/bin/memcached -d -u nobody -p 11211 -U 11211 -l 127.0.0.1 else echo "eq 0 - memcached running - do nothing" fi
The main command in this script is to check the process, use “ps” command with grep to make sure that it returns only the desired service and returns nothing if the service is not running.
该脚本中的主要命令是检查进程,将“ ps”命令与grep一起使用,以确保它仅返回所需的服务,如果服务未运行则不返回任何内容。
Once you have come up with the command to use, then only thing is to issue a start command to run the service.
一旦提出要使用的命令,那么唯一的事情就是发出启动命令来运行该服务。
Test the script to make sure it’s working as expected before setting it to run at regular intervals using crontab.
在使用crontab将脚本设置为定期运行之前,请对其进行测试以确保其正常运行。
每5分钟Crontab示例 (Crontab every 5 minutes example)
*/5 * * * * /Users/pankaj/Downloads/memcached_restart.sh > /Users/pankaj/Downloads/memcache_restart.log 2>&1
Crontab错误–找不到命令 (Crontab Error – command not found)
Note that crontab doesn’t consider environment variables such as PATH, so you have to always provide absolute path for any program or directory location. If you are getting “command not found” error while running a command in a crontab shell script and it runs fine if you execute yourself, then using the relative path will be the problem.
请注意,crontab不考虑诸如PATH之类的环境变量,因此您必须始终为任何程序或目录位置提供绝对路径。 如果在crontab shell脚本中运行命令时遇到“找不到命令”错误,并且如果您自己执行该命令也很好,那么使用相对路径将是问题。
Reference: Wikipedia
参考: 维基百科
翻译自: https://www.journaldev.com/580/crontab-example-every-5-minutes
crontab 示例
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/176438.html原文链接:https://javaforall.net
