ubuntu 下使用crontab定时执行java程序

来源:互联网 发布:淘宝开店要钱吗 编辑:程序博客网 时间:2024/05/22 06:05

题记

之前使用solr进行全文检索,涉及到检索更新问题,这里采用定时更新方法,现在使用的系统为ubuntu,因此考虑crontab.

解决思路

一.准备工具

  • 打包java程序jar
  • 安装crontab

二.编写crontab 脚本

过程

一.工具准备
1,制作jar包,可以通过java jar命令,也可以通过eclipse工具.
2.安装crontab
ubuntu上安装比较方便:

sudo apt-get install crontab

二.编写crontab脚本
1.认识crontab

Cron is a system daemon used to execute desired tasks (in the background) at designated times.

cron 属于一个守护进程,用来在特定的时间执行指定的任务,一般是后台运行.定义表达的很明确,使用时要确定时间和命令即可.

格式也简单:

minute (0-59), hour (0-23, 0 = midnight), day (1-31), month (1-12), weekday (0-6, 0 = Sunday), command

简单例子:

* * * * * command
表示每一分钟就执行一下command.

遇到的问题

(1)本身的java程序只是做一个测试,就是一个简单的弹出对话框,在编写crontab时候,出现没有反应的情况.
查看log—>/var/log/syslog
可以发现在日志文件中出现:No MTA installed, discarding output的问题.

根据查找资料发现crontab执行脚本时是不会直接错误的信息输出,而是会以邮件的形式发送到你的邮箱里,这时候就需要邮件服务器了,如果你没有安装邮件服务器,它就会报这个错。

通过在crontab脚本后面添加> /dev/null 2>&1,可以解决这个问题,也就是表示先将标准输出重定向到/dev/null,然后将标准错误重定向到标准输出,由于标准输出已经重定向到了/dev/null,因此标准错误也会重定向到/dev/null.

(2)开启crontab日志

  • 修改rsyslog文件,将/etc/rsyslog.d/50-default.conf文件中的#cron.*前的#删掉;
  • 重启rsyslog服务service rsyslog restart
  • 重启cron服务service cron restart

重启服务后,可还是没有出现对话框,查看日志没有错误出现,这就很奇怪了.
之后发现要启动GUI应用时候,需要启动系统的display.
It is possible to run gui applications via cronjobs. This can be done by telling cron which display to use.

00 06 * * * env DISPLAY=:0 gui_appname

The env DISPLAY=:0 portion will tell cron to use the current display (desktop) for the program

可以在crontab里面设置env DISPLAY,也可以在shell程序里面添加:export DISPLAY=:0.0
  • DISPLAY=:0 The env DISPLAY=:0 portion will tell cron to use the current display (desktop) for the program “gui_appname”.
  • DISPLAY=:0.0 if you have multiple monitors, don’t forget to specify on which one the program is to be run. The env DISPLAY=:0.0 portion will tell cron to use the first screen of the current display for the program “gui_appname”.

总结

  1. 查看官方资料(优选)及博文
  2. 遇到问题查看日志文件,一般情况,日志会记录的很详细
  3. 先从简单的例子开始,逐步测试,为了验证crontab是否运行 ,开始时候我就使用简单写入log功能测试,然后再进行java程序的测试
  4. 返回到第一步

附录编写代码

crontab代码:
每分钟执行test.sh脚本

PATH=/usr/sbin:/usr/bin:/sbin:/bin* * * * * /bin/bash /home/show_crontab/test.sh

test.sh脚本:

#!/bin/bashcd /home/show_crontab #进入目录export DISPLAY=:0.0 #启动GUI显示java -jar test.jar # 以防万一,这里的文件最好写成绝对路经

参考资料:
[1] https://help.ubuntu.com/community/CronHowto
[2]http://www.cnblogs.com/daxian2012/articles/2589894.html
[3]http://www.cnblogs.com/peida/archive/2013/01/08/2850483.html
[4]http://blog.csdn.net/huangyic1986/article/details/6731793
[5]http://bbs.chinaunix.net/thread-3650557-1-1.html

0 0
原创粉丝点击