Linux系统上实现定时重启Tomcat服务

因为使用阿里云部署服务器应用时,Tomcat服务经常由于内存不足出现OutOfMemoryError异常的情况。经常过几天就需要重启一次服务器,更要命的是不知道什么时候会由于内存不足导致无法访问,如果重启不及时严重影响系统体验。


为了解决上述问题,一方面是对tomcat配置做一些优化,网上有很多文章讲解如何优化Tomcat内存设置;另一方面就是写一个shell脚本,每天定时重启Tomcat服务。这里主要记录一下如何写shell脚本并且配置定时任务。本人使用的环境是阿里云Ubuntu服务器,以下配置在阿里云的Ubuntu服务器上能正常运行。

一、创建Shell脚本

新建一个tomcat.sh文件,输入以下内容:

#!/bin/bash
. /etc/profile
tomcatPath="/usr/local/tomcat"
binPath="$tomcatPath/bin"
echo "[info][$(date +'%F %H:%M:%S')]正在监控tomcat,路径:$tomcatPath"
pid=`ps -ef | grep tomcat | grep -w $tomcatPath | grep -v 'grep' | awk '{print $2}'`
if [ -n "$pid" ]; then
echo "[info][$(date +'%F %H:%M:%S')]tomcat进程为:$pid"
echo "[info][$(date +'%F %H:%M:%S')]tomcat已经启动,准备使用shutdown命令关闭..."
$binPath"/shutdown.sh"
sleep 2
pid=`ps -ef | grep tomcat | grep -w $tomcatPath | grep -v 'grep' | awk '{print $2}'`
if [ -n "$pid" ]; then
echo "[info][$(date +'%F %H:%M:%S')]使用shutdown命令关闭失败,准备kill进程..."
kill -9 $pid
echo "[info][$(date +'%F %H:%M:%S')]kill进程完毕!"
sleep 1
else
echo "[info][$(date +'%F %H:%M:%S')]使用shutdown命令关闭成功!"
fi
else
echo "[info][$(date +'%F %H:%M:%S')]tomcat未启动!"
fi
echo "[info][$(date +'%F %H:%M:%S')]准备启动tomcat..."
$binPath"/startup.sh"

脚本的逻辑比较简单,先查看tomcat进程是否存在,如果不存在则直接调用startup.sh命令启动tomcat,如果tomcat的进程存在则调用shutdown.sh命令停掉tomcat服务,有时会关闭失败,所以在检查一下tomcat进程时候还存在,如果存在就使用kill命令杀掉该进程,然后启动tomcat。
这里有一个地方需要注意,第二行代码(. /etc/profile)不能省掉,需要将环境变量引入到当前脚本环境中,要不然会导致启动定时任务时运行脚本失败,会报以下错误:

Neither the JAVA_HOME nor the JRE_HOME environment variable is defined At least one of these environment variable is needed to run this program

二、修改文件权限

要让脚本可以执行,当然要把文件设置为可执行文件了。

chmod 777 tomcat.sh

三、建立定时任务

在控制台上输入使用crontab -e 命令进入编辑crontab脚本,第一次输入该命令时需要选择编辑器。

选择vim编辑器编辑就可,在文件后面增加一条任务。(我的脚本文件路径是:/home/script/tomcat.sh)

然后保存并退出即可,接着使用crontab -l命令即可看到刚才新增的定时任务在列表里面。一般情况是直接生效,如果没有生效可以使用sudo service cron restart命令重启定时任务。

sudo service cron restart

四、定时任务描述语法

crontab中每一个定时任务的格式由6部分组成,分别是分钟、小时、天、月、星期以及命令,前5部分用来配置任务触发时机,中间使用空格隔开,如下:
minute hour day month dayofweek command

  • minute – 表示分钟,值的范围是从0到59的整数 
  • hour – 表示小时,值的范围是从0到23的整数 
  • day – 表示天,值的范围是从1到31的整数
  • month – 表示月,值的范围是从1到12的整数
  • dayofweek – 表示星期,值的范围是从0到6的整数 (0表示周日)
  • command – 需要执行的命令(/home/script/tomcat.sh > /home/script/shlog.txt表示执行tomcat.sh脚本,并且把结果日志打印到shlo.txt中)

 时间部分除了使用估计数字以外还可以配合星号(*),逗号(,),斜杠(/),横杠(-)组合来表示其他意义。

1. 星号(*)

表示任意值,比如:

30 01 * * * command #每天的1:30执行命令

2. 逗号(,)

表示指定的时间,比如:

30 01 1,10,20 * * command #每月的1号、10号、20号的1:30分执行命令

3. 斜杠(/)

表示每隔多长时间,比如:

* */2 * * * command #每个2小时执行一次命令

4. 横杠(-)

表示连续时间,比如:

* 1-7/1 * * * command #凌晨1点-7点之前每隔一小时执行一次命令

五、其他

以上哪里写的不对或者有待改进,欢迎大家提意见,谢谢!
下载地址:tomcat.sh
转载请注明出处:http://www.luoxudong.com/?p=330

有95人对 “Linux系统上实现定时重启Tomcat服务”留言了

  1. Gambling can be of many forms, with every type requiring
    its own legal structure. In Nevada, for example, there is what’s called
    a”lawsuit” A suit is an agreement or a contract between a individual placing a bet and the individual or group placing the cash at stake.
    In some states, a”gaming accounts” is created in which
    money deposited to the account is kept by a bookmaker and isn’t available to players; others allow online gambling but don’t permit offline gambling.

    Finally, you will find”rollover” trades in which the money in a participant’s account is withdrawn before it is used.

    In this way, the term gambling covers a wide range of trades and can refer to all of these,
    as each has its own set of conditions under which it may take place.

  2. Betting can be of several types, with each type requiring
    its own legal arrangement. In Nevada, for example, there is what’s called a”suit.” A suit is an agreement or a contract
    between a person placing a bet and the person or group
    putting the money at stake. In some countries, a”betting account” is created in which cash deposited into the account
    is retained by a bookmaker and is not accessible to gamers; others let online gambling but do not
    allow offline gaming. In the end, you will find”rollover”
    trades where the money in a player’s account is removed before it
    is used. This manner, the expression gaming covers a
    vast range of trades and may refer to every one of them,
    as each has its own set of conditions under which it can take place.

  3. With havin so much written content do you ever run into any
    issues of plagorism or copyright infringement? My website has a lot of unique content I’ve either written myself
    or outsourced but it looks like a lot of it is popping it up all over the internet without
    my agreement. Do you know any techniques to help stop content from being stolen? I’d genuinely appreciate it.

  4. I relish, result in I discovered exactly what I was looking
    for. You have ended my four day lengthy hunt! God Bless you
    man. Have a nice day. Bye

  5. What a information of un-ambiguity and preserveness of valuable
    knowledge regarding unexpected feelings.

  6. I got this website from my friend who told me concerning this web site
    and at the moment this time I am visiting this web page and reading very informative content
    here.

  7. Have you ever considered creating an e-book or guest authoring on other websites?
    I have a blog based on the same ideas you discuss and would really like to have you share some
    stories/information. I know my readers would appreciate your
    work. If you’re even remotely interested, feel free
    to send me an e mail.

  8. You can certainly see your expertise within the article you write.
    The arena hopes for even more passionate writers like you who are not afraid to say how they believe.
    Always go after your heart.

  9. I like the valuable info you provide in your articles.
    I’ll bookmark your blog and check again here frequently.
    I am quite sure I’ll learn many new stuff right here!
    Best of luck for the next!

  10. Hi there to every body, it’s my first pay a visit of this webpage; this
    blog includes amazing and really good stuff in support
    of visitors.

  11. Hi, i think that i noticed you visited my web site so
    i got here to go back the favor?.I’m attempting to find things to enhance my web site!I
    guess its ok to use a few of your concepts!!

  12. For all season-lengthy match bets and division betting, all bets stand
    regardless of group relocation, or a adjust to a group name, season length or playoff format.

  13. Wow, that’s what I was searching for, what a stuff!
    present here at this webpage, thanks admin of this web site.

  14. I am sure this article has touched all the internet users,
    its really really good piece of writing on building up new webpage.

  15. Excellent article! We will be linking to this
    particularly great content on our site. Keep up the great
    writing.

  16. My family every time say that I am killing my time here at net, however I know
    I am getting familiarity all the time by reading thes fastidious posts.

  17. Hello, I check your new stuff on a regular basis. Your
    writing style is awesome, keep doing what you’re doing!

  18. Hi there i am kavin, its my first time to commenting anywhere, when i read this paragraph i thought i could also make comment due to this
    sensible piece of writing.

  19. When I originally commented I seem to have clicked on the
    -Notify me when new comments are added- checkbox and now each time
    a comment is added I recieve four emails with the same comment.
    Is there an easy method you are able to remove me from that service?

    Kudos!

  20. Asking questions are really good thing if you are not understanding anything fully, however this piece of writing presents nice understanding even.

  21. I got this site from my buddy who shared with me concerning this website and at the moment this time
    I am browsing this web page and reading very informative articles
    or reviews here.

  22. I all the time emailed this blog post page to all my associates,
    because if like to read it next my contacts will too.

  23. Your means of explaining the whole thing in this article is truly good,
    every one can effortlessly know it, Thanks a lot.

  24. For the reason that the admin of this website
    is working, no uncertainty very soon it will be renowned, due
    to its feature contents.

  25. whoah this blog is excellent i really like studying your articles.
    Keep up the good work! You realize, lots of persons are looking round for this info, you could aid them
    greatly.

  26. Pretty section of content. I just stumbled upon your
    web site and in accession capital to claim that I get in fact loved account your blog posts.
    Any way I’ll be subscribing on your feeds or even I fulfillment you access constantly rapidly.

  27. I’m really impressed along with your writing skills as well as with the format
    for your weblog. Is this a paid theme or did you customize it your self?

    Either way keep up the nice high quality writing, it is uncommon to see a great weblog like this one these days..

  28. Fantastic beat ! I would like to apprentice even as
    you amend your web site, how can i subscribe for a blog
    web site? The account aided me a acceptable deal. I have been a little bit familiar of this your broadcast offered vivid transparent concept

  29. This is the perfect webpage for anybody who really wants to
    find out about this topic. You understand so much its almost tough
    to argue with you (not that I actually will need to…HaHa).
    You certainly put a brand new spin on a topic which has been written about for years.
    Excellent stuff, just excellent!

发表评论

邮箱地址不会被公开。